fastapi-utils icon indicating copy to clipboard operation
fastapi-utils copied to clipboard

[BUG] Error When Register Endpoint for Router of Instance of APIWebSocketRoute

Open HideyoshiNakazone opened this issue 1 year ago • 3 comments

Describe the bug When trying to add a @router.websocket endpoint to a CBV Router the following exception is throw:

Traceback (most recent call last):
  File "/home/user/Downloads/teste/main.py", line 7, in <module>
    @cbv(router)
     ^^^^^^^^^^^
  File "/home/user/.cache/pypoetry/virtualenvs/teste-4HLGbWUH-py3.12/lib/python3.12/site-packages/fastapi_utils/cbv.py", line 46, in decorator
    return _cbv(router, cls, *urls)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/.cache/pypoetry/virtualenvs/teste-4HLGbWUH-py3.12/lib/python3.12/site-packages/fastapi_utils/cbv.py", line 57, in _cbv
    _register_endpoints(router, cls, *urls)
  File "/home/user/.cache/pypoetry/virtualenvs/teste-4HLGbWUH-py3.12/lib/python3.12/site-packages/fastapi_utils/cbv.py", line 112, in _register_endpoints
    raise ValueError("The provided routes should be of type APIRoute")
ValueError: The provided routes should be of type APIRoute

To Reproduce

from fastapi import FastAPI, WebSocket, WebSocketDisconnect, APIRouter
from fastapi_utils.cbv import cbv

app = FastAPI()
router = APIRouter()

@cbv(router)
class WebSocketCBV:
    @router.websocket("/ws")
    async def websocket_endpoint(self, websocket: WebSocket):
        await websocket.accept()
        try:
            while True:
                data = await websocket.receive_text()
                await websocket.send_text(f"Message text was: {data}")
        except WebSocketDisconnect:
            print("Client disconnected")

app.include_router(router)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Expected behavior It to work since in your code the class WebSocketRoute is supported

Environment: Python Version: 3.12

Package Versions:

  • fastapi: 0.115.8
  • fastapi-utils: 0.8.0

Additional context Suggested solution in PR #358

HideyoshiNakazone avatar Feb 05 '25 00:02 HideyoshiNakazone

Hello! Anyone working on this issue?

kaziiriad avatar May 30 '25 08:05 kaziiriad

Opened a PR on that fixes this one. Thank you. #367

kaziiriad avatar May 30 '25 11:05 kaziiriad

Thanks @kaziiriad , i also did open a PR 358 It's discution is currently kinda stale

HideyoshiNakazone avatar Jun 02 '25 00:06 HideyoshiNakazone