pythonpython-3.xwebsocketpython-asyncio

Cannot access path in websockets.serve handler


I cannot find a way to access the path of a websocket connection, docs say Receiving the request path in the second parameter of connection handlers is deprecated.

python version: 3.12.6 websockets version: 14.1

async def handler(websocket: ServerConnection):
  print(websocket.path) ## AttributeError: 'ServerConnection' object has no attribute 'path'

async def main():
    server = await websockets.serve(
        handler,
        "0.0.0.0", 
        9000, 
    )

    print("Server started on 0.0.0.0:9000")

    await server.wait_closed()

if __name__ == "__main__":
    asyncio.run(main())


Solution

  • I can't account for the documentation, which appears to be wrong, but the websockets.asyncio.server.ServerConnection class instance has an attribute request of class websockets.http11.Request and it is this later instance that has a path attribute:

    ...
    
    async def handler(websocket: ServerConnection):
       print(websocket.request.path)
    
    ...