From 30e66144ce51054fe45013f2f34e07b6fe474001 Mon Sep 17 00:00:00 2001 From: Rodja Trappe Date: Wed, 7 Feb 2024 04:58:25 +0100 Subject: [PATCH] strip root_path to make ASGIServer from socketio compatible with mounting as sub-app (fixes #2468 and #2515) --- examples/fastapi/frontend.py | 3 ++- nicegui/nicegui.py | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/examples/fastapi/frontend.py b/examples/fastapi/frontend.py index 9669298c4..a0e1d9d2a 100644 --- a/examples/fastapi/frontend.py +++ b/examples/fastapi/frontend.py @@ -4,7 +4,7 @@ def init(fastapi_app: FastAPI) -> None: - @ui.page('/show') + @ui.page('/') def show(): ui.label('Hello, FastAPI!') @@ -14,5 +14,6 @@ def show(): ui.run_with( fastapi_app, + mount_path='/gui', # NOTE this can be omitted if you want the paths passed to @ui.page to be at the root storage_secret='pick your private secret here', # NOTE setting a secret is optional but allows for persistent storage per user ) diff --git a/nicegui/nicegui.py b/nicegui/nicegui.py index 8594d2531..9edd51783 100644 --- a/nicegui/nicegui.py +++ b/nicegui/nicegui.py @@ -30,10 +30,23 @@ async def _lifespan(_: App): yield await _shutdown() + +class SocketIOASGIApp(socketio.ASGIApp): + """Custom ASGI app to handle root_path. + + This is a workaround for https://github.com/miguelgrinberg/python-engineio/pull/345 + """ + + async def __call__(self, scope, receive, send): + if 'root_path' in scope and scope['path'].startswith(scope['root_path']): + scope['path'] = scope['path'][len(scope['root_path']):] + return await super().__call__(scope, receive, send) + + core.app = app = App(default_response_class=NiceGUIJSONResponse, lifespan=_lifespan) # NOTE we use custom json module which wraps orjson core.sio = sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins='*', json=json) -sio_app = socketio.ASGIApp(socketio_server=sio, socketio_path='/_nicegui_ws/socket.io') +sio_app = SocketIOASGIApp(socketio_server=sio, socketio_path='/socket.io') app.mount('/_nicegui_ws/', sio_app)