Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async def handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
try:
await ws.send_bytes(b'started')
await ws.receive_bytes()
finally:
closed.set_result(1)
return ws
def test_can_prepare_ok(make_request):
req = make_request('GET', '/', protocols=True)
ws = WebSocketResponse(protocols=('chat',))
assert(True, 'chat') == ws.can_prepare(req)
async def _handle_websocket(
self, request: web.Request, addon: Addon, path: str
) -> web.WebSocketResponse:
"""Ingress route for websocket."""
if hdrs.SEC_WEBSOCKET_PROTOCOL in request.headers:
req_protocols = [
str(proto.strip())
for proto in request.headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(",")
]
else:
req_protocols = ()
ws_server = web.WebSocketResponse(
protocols=req_protocols, autoclose=False, autoping=False
)
await ws_server.prepare(request)
# Preparing
url = self._create_url(addon, path)
source_header = _init_header(request, addon)
# Support GET query
if request.query_string:
url = "{}?{}".format(url, request.query_string)
# Start proxy
async with self.sys_websession.ws_connect(
url,
headers=source_header,
async def wrapper(request):
access_control(app, request)
ws = aiohttp.web.WebSocketResponse()
await ws.prepare(request)
try:
await handler(app, request, ws)
except Exception as e:
log.exception(
'An error occurred in WebSocket handler %s',
handler.__name__)
return ws
async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
request.app['agent'].ui_socket = ws
print(request.app['agent'].ui_socket)
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
if msg.data == 'close':
await ws.close()
else:
await ws.send_str(msg.data + '/answer')
elif msg.type == aiohttp.WSMsgType.ERROR:
print('ws connection closed with exception %s' %
ws.exception())
request.app['agent'].ui_socket = None
print('websocket connection closed')
async def heartbeat(request):
ws = web.WebSocketResponse(timeout=60*60*24*365)
if servermode and server_ready:
asyncio.get_event_loop().create_task(cravat_multiuser.update_last_active(request))
await ws.prepare(request)
async for msg in ws:
pass
return ws
async def __call__(self):
ws = web.WebSocketResponse()
await ws.prepare(self.request)
async for msg in ws:
if msg.tp == aiohttp.MsgType.text:
if msg.data == 'close':
await ws.close()
else:
ws.send_str(msg.data + '/answer')
elif msg.tp == aiohttp.MsgType.error:
logger.debug('ws connection closed with exception {0:s}'
.format(ws.exception()))
logger.debug('websocket connection closed')
return {}
async def _ws_handler(self, request, group):
"""
Handle websocket connections.
This includes:
* new connections
* closed connections
* messages
"""
ws_client = web.WebSocketResponse()
await ws_client.prepare(request)
session = None
if self.websockets[group]["authenticated"]:
session = await get_session(request)
if session.new:
self.logger.debug('websocket: not logged in')
if asyncio.iscoroutinefunction(ws_client.send_str):
await ws_client.send_str(json.dumps({'status': 401, 'text': "Unauthorized"}))
else:
ws_client.send_str(json.dumps({'status': 401, 'text': "Unauthorized"}))
ws_client.close()
return ws_client
ws_client.cirrina = CirrinaWSContext(request, session)
self.websockets[group]["connections"].append(ws_client)
async def handler(request: web.Request) -> web.Response:
app = request.app
if request.path == '/':
return web.Response(text=app['get_index'](), content_type='text/html')
if request.path == '/ws':
ws = web.WebSocketResponse(autoclose=False)
await ws.prepare(request)
log.info(f'Browser connected: {id(ws)}')
app['wss'].add(ws)
async for msg in ws:
app['ws_msg_handler'](msg.json())
log.info(f'Browser disconnected: {id(ws)}')
app['wss'].remove(ws)
return ws
raise web.HTTPNotFound()
async def connect_websocket (request):
global install_state
global install_ws
if not install_state:
install_state['stage'] = ''
install_state['message'] = ''
install_state['module_name'] = ''
install_state['module_version'] = ''
install_state['cur_chunk'] = 0
install_state['total_chunks'] = 0
install_state['cur_size'] = 0
install_state['total_size'] = 0
install_state['update_time'] = time.time()
install_state['kill_signal'] = False
last_update_time = install_state['update_time']
install_ws = web.WebSocketResponse(timeout=60*60*24*365)
await install_ws.prepare(request)
while True:
try:
await asyncio.sleep(1)
except concurrent.futures._base.CancelledError:
return install_ws
if last_update_time < install_state['update_time']:
last_update_time = await send_socket_msg()
return install_ws