`Async for` can be used to iterate over a websocket's incoming messages
See original GitHub issueIs your feature request related to a problem? Please describe.
When creating a websocket server I’d like to use async for
to iterate over the incoming messages from a connection. This is a feature that the websockets lib uses. Currently, if you try to use async for
you get the following error:
TypeError: 'async for' requires an object with __aiter__ method, got WebsocketImplProtocol
Describe the solution you’d like
Ideally, I could run something like the following on a Sanic websocket route:
@app.websocket("/")
async def feed(request, ws):
async for msg in ws:
print(f'received: {msg.data}')
await ws.send(msg.data)
Additional context This was originally discussed on the sanic-support channel on the discord server
Issue Analytics
- State:
- Created a year ago
- Reactions:3
- Comments:11 (9 by maintainers)
Top Results From Across the Web
Python - Async callback/receiver for WebSocket - Stack Overflow
The inner loop processes one incoming message at a time. If you are connected, and no messages are coming in from the server,...
Read more >Asynchronous Websockets -- a quick tutorial
This holds our main loop for incoming messages from the client. An incoming message gets stored into a global after which we job...
Read more >Control not released while sending multiple messages #865
Example code: Here's a simple server that sends 20 packets of data to the client. I use time.sleep(1) instead of asyncio.
Read more >Getting started — websockets 6.0 documentation
Iteration terminates when the client disconnects. recv() raises a ConnectionClosed exception when the client disconnects, which breaks out of the while True ......
Read more >Asyncing Feeling about JavaScript Generators - Big Nerd Ranch
This async iterator waits to receive a message, then yield s the data attribute of the WebSocket's MessageEvent . The oncePromise() function is ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Code clarity should probably take precedence since there really is no speed difference either way 😃
I’d like it to have same behavior as the websockets lib