-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
implement manage ws connections, publish to wroker process topic
- Loading branch information
Showing
2 changed files
with
57 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,37 @@ | ||
from aiohttp import web, WSMsgType | ||
import json | ||
|
||
from aiohttp import web, WSMsgType, WSCloseCode | ||
|
||
|
||
class WebSocketView(web.View): | ||
|
||
def __init__(self, *args, **kwargs): | ||
super(WebSocketView, self).__init__(*args, **kwargs) | ||
self.app = self.request.app | ||
self.logger = self.app.logger | ||
|
||
async def get(self): | ||
|
||
ws = web.WebSocketResponse() | ||
await ws.prepare(self.request) | ||
|
||
async for msg in ws: | ||
if msg.type == WSMsgType.TEXT: | ||
if msg.data == 'close': | ||
await ws.close() | ||
else: | ||
ws.send_str(msg.data + '/answer') | ||
elif msg.type == WSMsgType.ERROR: | ||
print('ws connection closed with exception %s' % | ||
ws.exception()) | ||
|
||
print('websocket connection closed') | ||
ws_id = id(ws) | ||
self.logger.debug('[%s] New websocket connection', ws_id) | ||
self.app.handle_ws_connect(ws, self) | ||
|
||
async for msg_raw in ws: | ||
if msg_raw.tp == WSMsgType.TEXT: | ||
try: | ||
msg = json.loads(msg_raw.data) | ||
self.logger.debug('[%s] Publish message %s to redis', ws_id, msg) | ||
await self.app.publish_message_to_worker(ws, msg) | ||
except Exception as e: | ||
self.logger.error('[%s] Invalid message format. Exception: %s', ws_id, e) | ||
await ws.close(code=WSCloseCode.UNSUPPORTED_DATA, message=str(e)) | ||
break | ||
|
||
elif msg_raw.tp == WSMsgType.ERROR: | ||
self.logger.error('[%s] ERROR WS connection closed with exception: %s', ws_id, ws.exception()) | ||
|
||
self.logger.debug('[%s] Websocket connection closed', ws_id) | ||
self.app.handle_ws_disconnect(ws) | ||
return ws |