aiohttp.WSMsgType.TEXT

Here are the examples of the python api aiohttp.WSMsgType.TEXT taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

20 Examples 7

Example 1

Project: aiohttp
License: View license
Source File: test_test_utils.py
@asyncio.coroutine
def test_client_websocket(loop, test_client):
    resp = yield from test_client.ws_connect("/websocket")
    resp.send_str("foo")
    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.TEXT
    assert "foo" in msg.data
    resp.send_str("close")
    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.CLOSE

Example 2

Project: aiohttp
License: View license
Source File: test_websocket_parser.py
Function: test_simple_text
def test_simple_text(buf, out, parser):
    buf.extend(build_frame(b'text', WSMsgType.TEXT))
    next(parser)
    parser.send(b'')
    res = out._buffer[0]
    assert res == ((WSMsgType.TEXT, 'text', ''), 4)

Example 3

Project: aiohttp
License: View license
Source File: test_websocket_parser.py
def test_simple_text_unicode_err(buf, parser):
    buf.extend(
        build_frame(b'\xf4\x90\x80\x80', WSMsgType.TEXT))
    with pytest.raises(WebSocketError) as ctx:
        next(parser)

    assert ctx.value.code == WSCloseCode.INVALID_TEXT

Example 4

Project: aiohttp
License: View license
Source File: test_websocket_parser.py
Function: test_continuation
def test_continuation(out, parser):
    cur = 0

    def parse_frame(buf, cont=False):
        nonlocal cur
        yield
        if cur == 0:
            cur = 1
            return (0, WSMsgType.TEXT, b'line1')
        else:
            return (1, WSMsgType.CONTINUATION, b'line2')

    with mock.patch('aiohttp._ws_impl.parse_frame') as m_parse_frame:
        m_parse_frame.side_effect = parse_frame
        next(parser)
        parser.send(b'')
        parser.send(b'')
    res = out._buffer[0]
    assert res == (WSMessage(WSMsgType.TEXT, 'line1line2', ''), 10)

Example 5

Project: aiohttp
License: View license
Source File: test_websocket_parser.py
def test_continuation_err(out, parser):
    cur = 0

    def parse_frame(buf, cont=False):
        nonlocal cur
        yield
        if cur == 0:
            cur = 1
            return (0, WSMsgType.TEXT, b'line1')
        else:
            return (1, WSMsgType.TEXT, b'line2')

    with mock.patch('aiohttp._ws_impl.parse_frame') as m_parse_frame:
        m_parse_frame.side_effect = parse_frame
        next(parser)
        parser.send(b'')
        with pytest.raises(WebSocketError):
            parser.send(b'')

Example 6

Project: aiohttp
License: View license
Source File: test_websocket_parser.py
def test_continuation_with_close_unicode_err(out, parser):
    frames = [
        (0, WSMsgType.TEXT, b'line1'),
        (0, WSMsgType.CLOSE,
         build_close_frame(1000, b'\xf4\x90\x80\x80', noheader=True)),
        (1, WSMsgType.CONTINUATION, b'line2')]

    def parse_frame(buf, cont=False):
        yield
        return frames.pop(0)

    with mock.patch('aiohttp._ws_impl.parse_frame') as m_parse_frame:
        m_parse_frame.side_effect = parse_frame
        next(parser)
        parser.send(b'')
        with pytest.raises(WebSocketError) as ctx:
            parser.send(b'')

    assert ctx.value.code == WSCloseCode.INVALID_TEXT

Example 7

Project: aiohttp
License: View license
Source File: test_websocket_parser.py
def test_continuation_with_close_bad_code(out, parser):
    frames = [
        (0, WSMsgType.TEXT, b'line1'),
        (0, WSMsgType.CLOSE,
         build_close_frame(1, b'test', noheader=True)),
        (1, WSMsgType.CONTINUATION, b'line2')]

    def parse_frame(buf, cont=False):
        yield
        return frames.pop(0)

    with mock.patch('aiohttp._ws_impl.parse_frame') as m_parse_frame:
        m_parse_frame.side_effect = parse_frame
        next(parser)
        parser.send(b'')
        with pytest.raises(WebSocketError) as ctx:
            parser.send(b'')

        assert ctx.value.code == WSCloseCode.PROTOCOL_ERROR

Example 8

Project: aiohttp
License: View license
Source File: test_websocket_parser.py
def test_continuation_with_close_bad_payload(out, parser):
    frames = [
        (0, WSMsgType.TEXT, b'line1'),
        (0, WSMsgType.CLOSE, b'1'),
        (1, WSMsgType.CONTINUATION, b'line2')]

    def parse_frame(buf, cont=False):
        yield
        return frames.pop(0)

    with mock.patch('aiohttp._ws_impl.parse_frame') as m_parse_frame:
        m_parse_frame.side_effect = parse_frame
        next(parser)
        parser.send(b'')
        with pytest.raises(WebSocketError) as ctx:
            parser.send(b'')

        assert ctx.value.code, WSCloseCode.PROTOCOL_ERROR

Example 9

Project: aiohttp
License: View license
Source File: test_websocket_parser.py
def test_msgtype_aliases():
    assert aiohttp.WSMsgType.TEXT == aiohttp.WSMsgType.text
    assert aiohttp.WSMsgType.BINARY == aiohttp.WSMsgType.binary
    assert aiohttp.WSMsgType.PING == aiohttp.WSMsgType.ping
    assert aiohttp.WSMsgType.PONG == aiohttp.WSMsgType.pong
    assert aiohttp.WSMsgType.CLOSE == aiohttp.WSMsgType.close
    assert aiohttp.WSMsgType.CLOSED == aiohttp.WSMsgType.closed
    assert aiohttp.WSMsgType.ERROR == aiohttp.WSMsgType.error

Example 10

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_receive_bytes_nonsbytes(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)

    @asyncio.coroutine
    def receive():
        return WSMessage(WSMsgType.TEXT, 'data', b'')

    ws.receive = receive

    with pytest.raises(TypeError):
        yield from ws.receive_bytes()

Example 11

Project: aiohttp-devtools
License: View license
Source File: serve.py
Function: websocket_handler
async def websocket_handler(request):
    ws = web.WebSocketResponse(timeout=0.01)
    url = None
    await ws.prepare(request)

    async for msg in ws:
        if msg.tp == WSMsgType.TEXT:
            try:
                data = json.loads(msg.data)
            except json.JSONDecodeError as e:
                logger.error('JSON decode error: %s', str(e))
            else:
                command = data['command']
                if command == 'hello':
                    if 'http://livereload.com/protocols/official-7' not in data['protocols']:
                        logger.error('live reload protocol 7 not supported by client %s', msg.data)
                        ws.close()
                    else:
                        handshake = {
                            'command': 'hello',
                            'protocols': [
                                'http://livereload.com/protocols/official-7',
                            ],
                            'serverName': 'livereload-aiohttp',
                        }
                        ws.send_str(json.dumps(handshake))
                elif command == 'info':
                    logger.debug('browser connected: %s', data)
                    url = '/' + data['url'].split('/', 3)[-1]
                    request.app[WS].append((ws, url))
                else:
                    logger.error('Unknown ws message %s', msg.data)
        elif msg.tp == WSMsgType.ERROR:
            logger.error('ws connection closed with exception %s', ws.exception())
        else:
            logger.error('unknown websocket message type %s, data: %s', WS_TYPE_LOOKUP[msg.tp], msg.data)

    if url is None:
        logger.warning('browser disconnected, appears no websocket connection was made')
    else:
        logger.debug('browser disconnected')
        request.app[WS].remove((ws, url))
    return ws

Example 12

Project: aioreactive
License: View license
Source File: autocomplete.py
async def websocket_handler(request):
    print("WebSocket opened")

    stream = AsyncStream()

    # Line break before binary operator is more readable. Disable W503
    xs = (stream
          | op.map(lambda x: x["term"])
          | op.filter(lambda text: len(text) > 2)
          | op.debounce(0.75)
          | op.distinct_until_changed()
          | op.map(search_wikipedia)
          | op.switch_latest()
          )

    ws = web.WebSocketResponse()
    await ws.prepare(request)

    async def asend(value):
        ws.send_str(value)

    async def athrow(ex):
        print(ex)

    await start(xs, FuncSink(asend, athrow))

    async for msg in ws:
        if msg.type == aiohttp.WSMsgType.TEXT:
            obj = json.loads(msg.data)
            await stream.asend(obj)

        elif msg.type == aiohttp.WSMsgType.ERROR:
            print('ws connection closed with exception %s' % ws.exception())

    print('websocket connection closed')
    return ws

Example 13

Project: aiohttp
License: View license
Source File: test_client_ws_functional.py
@asyncio.coroutine
def test_close_timeout(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)
        yield from ws.receive_bytes()
        ws.send_str('test')
        yield from asyncio.sleep(10, loop=loop)

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)
    resp = yield from client.ws_connect('/', timeout=0.2, autoclose=False)

    resp.send_bytes(b'ask')

    msg = yield from resp.receive()
    assert msg.data == 'test'
    assert msg.type == aiohttp.WSMsgType.TEXT

    msg = yield from resp.close()
    assert resp.closed
    assert isinstance(resp.exception(), asyncio.TimeoutError)

Example 14

Project: aiohttp
License: View license
Source File: test_test_utils.py
def _create_example_app(loop):

    @asyncio.coroutine
    def hello(request):
        return web.Response(body=b"Hello, world")

    @asyncio.coroutine
    def websocket_handler(request):

        ws = web.WebSocketResponse()
        yield from ws.prepare(request)
        msg = yield from ws.receive()
        if msg.type == aiohttp.WSMsgType.TEXT:
            if msg.data == 'close':
                yield from ws.close()
            else:
                ws.send_str(msg.data + '/answer')

        return ws

    @asyncio.coroutine
    def cookie_handler(request):
        resp = web.Response(body=b"Hello, world")
        resp.set_cookie('cookie', 'val')
        return resp

    app = web.Application(loop=loop)
    app.router.add_route('*', '/', hello)
    app.router.add_route('*', '/websocket', websocket_handler)
    app.router.add_route('*', '/cookie', cookie_handler)
    return app

Example 15

Project: aiohttp
License: View license
Source File: test_websocket_parser.py
def test_continuation_with_ping(out, parser):
    frames = [
        (0, WSMsgType.TEXT, b'line1'),
        (0, WSMsgType.PING, b''),
        (1, WSMsgType.CONTINUATION, b'line2'),
    ]

    def parse_frame(buf, cont=False):
        yield
        return frames.pop(0)

    with mock.patch('aiohttp._ws_impl.parse_frame') as m_parse_frame:
        m_parse_frame.side_effect = parse_frame
        next(parser)
        parser.send(b'')
        parser.send(b'')
        parser.send(b'')
    res = out._buffer[0]
    assert res == (WSMessage(WSMsgType.PING, b'', ''), 0)
    res = out._buffer[1]
    assert res == (WSMessage(WSMsgType.TEXT, 'line1line2', ''), 10)

Example 16

Project: aiohttp
License: View license
Source File: test_websocket_parser.py
def test_continuation_with_close(out, parser):
    frames = [
        (0, WSMsgType.TEXT, b'line1'),
        (0, WSMsgType.CLOSE,
         build_close_frame(1002, b'test', noheader=True)),
        (1, WSMsgType.CONTINUATION, b'line2'),
    ]

    def parse_frame(buf, cont=False):
        yield
        return frames.pop(0)

    with mock.patch('aiohttp._ws_impl.parse_frame') as m_parse_frame:
        m_parse_frame.side_effect = parse_frame
        next(parser)
        parser.send(b'')
        parser.send(b'')
        parser.send(b'')
        res = out._buffer[0]
    assert res, (WSMessage(WSMsgType.CLOSE, 1002, 'test'), 0)
    res = out._buffer[1]
    assert res == (WSMessage(WSMsgType.TEXT, 'line1line2', ''), 10)

Example 17

Project: aiohttp
License: View license
Source File: test_websocket_parser.py
def test_continuation_with_close_empty(out, parser):
    frames = [
        (0, WSMsgType.TEXT, b'line1'),
        (0, WSMsgType.CLOSE, b''),
        (1, WSMsgType.CONTINUATION, b'line2'),
    ]

    def parse_frame(buf, cont=False):
        yield
        return frames.pop(0)

    with mock.patch('aiohttp._ws_impl.parse_frame') as m_parse_frame:
        m_parse_frame.side_effect = parse_frame
        next(parser)
        parser.send(b'')
        parser.send(b'')
        parser.send(b'')

    res = out._buffer[0]
    assert res, (WSMessage(WSMsgType.CLOSE, 0, ''), 0)
    res = out._buffer[1]
    assert res == (WSMessage(WSMsgType.TEXT, 'line1line2', ''), 10)

Example 18

@asyncio.coroutine
def test_send_recv_text(loop, test_client):

    closed = helpers.create_future(loop)

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)
        msg = yield from ws.receive_str()
        ws.send_str(msg+'/answer')
        yield from ws.close()
        closed.set_result(1)
        return ws

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)

    ws = yield from client.ws_connect('/')
    ws.send_str('ask')
    msg = yield from ws.receive()
    assert msg.type == aiohttp.WSMsgType.TEXT
    assert 'ask/answer' == msg.data

    msg = yield from ws.receive()
    assert msg.type == aiohttp.WSMsgType.CLOSE
    assert msg.data == 1000
    assert msg.extra == ''

    assert ws.closed
    assert ws.close_code == 1000

    yield from closed

Example 19

@asyncio.coroutine
def test_send_recv_json(loop, test_client):
    closed = helpers.create_future(loop)

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)
        data = yield from ws.receive_json()
        ws.send_json({'response': data['request']})
        yield from ws.close()
        closed.set_result(1)
        return ws

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)

    ws = yield from client.ws_connect('/')

    ws.send_str('{"request": "test"}')
    msg = yield from ws.receive()
    data = msg.json()
    assert msg.type == aiohttp.WSMsgType.TEXT
    assert data['response'] == 'test'

    msg = yield from ws.receive()
    assert msg.type == aiohttp.WSMsgType.CLOSE
    assert msg.data == 1000
    assert msg.extra == ''

    yield from ws.close()

    yield from closed

Example 20

Project: lrrbot
License: View license
Source File: pubsub.py
	async def message_pump(self):
		next_timeout = 1
		error = False
		while True:
			try:
				log.debug("Connecting to wss://pubsub-edge.twitch.tv")
				async with http.http_request_session.ws_connect("wss://pubsub-edge.twitch.tv") as pubsub:
					log.debug("Connected to wss://pubsub-edge.twitch.tv")
					self.stream = pubsub
					self.ping_task = asyncio.ensure_future(self._ping())
					self.ping_task.add_done_callback(utils.check_exception)

					# TODO: coalesce topics
					for_user = {}
					for topic, data in self.topics.items():
						for_user.setdefault(data.user, []).append(topic)
					for user, topics in for_user.items():
						self._listen(topics, user)

					async for message in pubsub:
						if message.type == aiohttp.WSMsgType.TEXT:
							next_timeout = 1
							msg = json.loads(message.data)
							log.debug("New message: %r", msg)
							if msg['type'] == 'RESPONSE':
								if msg['error']:
									log.error("Error in response to message %s: %s", msg['nonce'], msg['error'])
							elif msg['type'] == 'MESSAGE':
								signals.signal(msg['data']['topic']).send(self, message=json.loads(msg['data']['message']))
							elif msg['type'] == 'RECONNECT':
								await pubsub.close()
								error = False
								break
							elif msg['type'] == 'PONG':
								log.debug("Received a PONG")
								self.disconnect_task.cancel()
								self.disconnect_task = None
						elif message.type == aiohttp.WSMsgType.CLOSED:
							error = True
							break
						elif message.type == aiohttp.WSMsgType.ERROR:
							raise Exception("Error reading message") from pubsub.exception()
			except utils.PASSTHROUGH_EXCEPTIONS:
				raise
			except Exception:
				log.exception("Exception in PubSub message task")
				error = True
			finally:
				self.ping_task.cancel()
				self.ping_task = None
				if self.disconnect_task is not None:
					self.disconnect_task.cancel()
					self.disconnect_task = None
				self.stream = None

			jitter = random.gauss(0, next_timeout / 4)
			jitter = max(-next_timeout, min(jitter, next_timeout))

			await asyncio.sleep(min(1, next_timeout + jitter))

			if error:
				next_timeout = min(next_timeout * 2, 120)