O
O
Oleg Vedernikov2018-06-30 15:48:04
Python
Oleg Vedernikov, 2018-06-30 15:48:04

How to correctly create a ws connection?

How to correctly create a ws connection?
For educational purposes, I began to get acquainted with aiohtt.
I am doing a pet project where I use VueJs on the front, and aiohttp on the back, respectively.
Faced the task of how to properly make real-time notifications, for example, as it is implemented in VK, when new messages arrive / friends are added / other.
On the front, if the user is authorized, then a ws connection to the server is automatically established. On the back, there is a ws handler:
ws = new WebSocket(URL);

async def websocket_handler(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    request.app['websockets']['user_id'] = ws

    async for msg in ws:
        pass   # корректна ли эта инструкция, чтобы при потери соединения выполнялась строчка ниже?
    request.app['websockets'].remove(ws)

    return ws

There are also several endpoints (new_message, new_friend, etc) that should send some information to this web socket
async def new_message(request):
    # тут валидируем и сохраняем сообщение

    # отправляем данные в сокет
    ws = request.app['websockets']['receiver_id']:
    ws.send_str('new message detail')

It is expected that no matter what part of the application the client is in, he will always receive notifications about new events, because. The websocket is opened once the user logs in and does not close until the connection is lost.
Is it right or wrong to do this? Why?
How will the application behave if, for example, 10k connections are open at the same time?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-06-30
@kila

In general, everything is correct, only await ws.send_str('new message detail')instead it is passworth adding

if msg.type == WSMsgType.ERROR:
    какая-нибудь реакция на ошибку

This is what aiohttp was created for.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question