fasthtml icon indicating copy to clipboard operation
fasthtml copied to clipboard

Update ws example

Open mattlink opened this issue 1 year ago • 3 comments

Adds another endpoint to examples/basic_ws.py which illustrates how to read data from the websocket.

It is not clear from the existing example (or docs, currently) that you can specify a data argument to the handler function to effectively get the contents of ws.receive(). There are other hidden arguments which seem to correspond to these annotations

mattlink avatar Jul 31 '24 04:07 mattlink

Thanks - this is a good idea. I guess it also probably needs something on the page demonstrating its use?

jph00 avatar Jul 31 '24 09:07 jph00

@mattlink just bumping this...

jph00 avatar Aug 11 '24 08:08 jph00

Another issue that I think should be covered in docs/examples is how to pass a variable from the web socket URL path. It is done via ws param. Here is an example snippet

from starlette.websockets import WebSocket

@rt.ws('/wscon/{session_id}', conn=on_connect, disconn=on_disconnect)
async def ws_func(ws:WebSocket, data, send):
    session_id = ws.path_params.get("session_id")
    #... rest of the code

NB: you can pass URL path param to on_connect(), on_disconnect() functions as well.

Kvit avatar Feb 13 '25 05:02 Kvit