Question: Using handler decorators on methods #3173
|
Reported by @skewty in Discord: <#1212105750608871445>: The following MCVE ish code works, but for reasons outlined in this (and surrounding messages) OP prefers to use a web socket handler that is a method. Changing from litestar import Litestar, WebSocket, websocket
class Something:
@websocket("/ws")
async def handler(socket: WebSocket) -> None:
await socket.accept()
app = Litestar([Something().handler])As per docs
Shouldn't an error be raised? Is this usage recommend? |
Replies: 4 comments
|
So I tried to implement this as a stand-alone function and discovered that any dependency named "self" breaks the route. |
|
Also note the handler copies some code from: https://docs.litestar.dev/2/usage/channels.html#managing-history But when running it: It appears the sample code in the documentation is no longer valid. async with channels.subscribe(["some_channel"]) as subscriber:
# should be changed to
async with channels.start_subscription(["some_channel"]) as subscriber: |
|
The issue here is that at the time the You can fix this by changing how you pass the handlers: from litestar import Litestar, WebSocket, websocket
class Something:
async def handler(socket: WebSocket) -> None:
await socket.accept()
app = Litestar([websocket("/ws")(Something().handler)])Litestar itself does something similar in the litestar/litestar/channels/plugin.py Lines 117 to 126 in 1332983
No, I wouldn't recommend it, and I would advise you to change how you've set up your code that this is a requirement. Usually there are ways to work around this. |
|
You can also make the class a from litestar import Litestar, WebSocket, websocket, Controller
class Something(Controller):
@websocket("/ws")
async def handler(self, socket: WebSocket) -> None:
await socket.accept()
app = Litestar([Something]) |
The issue here is that at the time the
@websocketdecorator is passedSomething.handler, the function is still unbound (i.e. theselfargument won't receive the instance you created automatically, because it doesn't exist yet).You can fix this by changing how you pass the handlers:
Litestar itself does something similar in the
ChannelsPlugin:litestar/litestar/channels/plugin.py
Lines 117 to 126 in 1332983