-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Async for
can be used to iterate over a websocket's incoming messages
#2464
Comments
I will take a look and see what can be done, if no one has started working on it. Thanks for creating the issue! |
This feature was available in earlier version of sanic years ago, maybe earlier version uses websockets internally?
|
You can do it without async def __aiter__(self):
while True:
yield await self.recv() As a user workaround, I suppose one can monkey patch that on Sanic's websocket, but hopefully @ChihweiLHBird gets the patch done and merged in time for the upcoming Sanic 22.6 release. |
I think async def test_anext():
while True:
await anext(ws) |
My question is, should we make the whole async def recv_generator(self):
while True:
yield await self.recv() Any opinion? |
I’d like it to have same behavior as the websockets lib |
☝️ |
The whole purpose of |
Because this is Sanic, I ran a benchmark. The built-in async iterator is some nanoseconds faster per call but while barely measurable, the difference is utterly negligible to anything else that receiving from a WebSocket does. The benchmark code (written on ipython prompt and timed with Also the situation reverses if only a few messages are to be received within the loop, as the built-in iterator still needs to be constructed, while returning One thing to consider is what to do if the websocket is closed, should it exit the loop cleanly or just raise some exception? Probably the latter, which doesn't then need any extra work. The loop will then never exit normally. |
Okay, I agree with you. Benchmark matters and I think the scenario of large number of messages is more common.
|
Code clarity should probably take precedence since there really is no speed difference either way :) |
Is 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 useasync 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:
Additional context
This was originally discussed on the sanic-support channel on the discord server
The text was updated successfully, but these errors were encountered: