Skip to content

Commit

Permalink
Fix aio-libs#976: Add support for websocket send_json and receive_json
Browse files Browse the repository at this point in the history
  • Loading branch information
Vitalie Maldur committed Jul 23, 2016
1 parent a5b75e0 commit b117446
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
7 changes: 7 additions & 0 deletions aiohttp/web_ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,13 @@ def send_bytes(self, data):
type(data))
self._writer.send(data, binary=True)

def send_json(self, data, *, dumps=json.dumps):
if self._writer is None:
raise RuntimeError('Call .prepare() first')
if self._closed:
raise RuntimeError('websocket connection is closing')
self._writer.send(dumps(data), binary=False)

@asyncio.coroutine
def wait_closed(self): # pragma: no cover
warnings.warn(
Expand Down
14 changes: 14 additions & 0 deletions aiohttp/websocket_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import asyncio

import sys
import json
from enum import IntEnum

from .websocket import Message
Expand Down Expand Up @@ -88,6 +89,11 @@ def send_bytes(self, data):
type(data))
self._writer.send(data, binary=True)

def send_json(self, data, *, dumps=json.dumps):
if self._closed:
raise RuntimeError('websocket connection is closed')
self._writer.send(dumps(data), binary=False)

@asyncio.coroutine
def close(self, *, code=1000, message=b''):
if not self._closed:
Expand Down Expand Up @@ -171,6 +177,14 @@ def receive(self):
finally:
self._waiting = False

def receive_json(self, *, loads=json.loads):
msg = yield from self.receive()
if msg.tp != MsgType.text:
raise TypeError(
"Received message {}:{!r} is not str".format(msg.tp, msg.data)
)
return msg.json(loads=loads)

if PY_35:
@asyncio.coroutine
def __aiter__(self):
Expand Down

0 comments on commit b117446

Please sign in to comment.