Skip to content

Commit

Permalink
strip root_path to make ASGIServer from socketio compatible with moun…
Browse files Browse the repository at this point in the history
…ting as sub-app (fixes #2468 and #2515)
  • Loading branch information
rodja committed Feb 7, 2024
1 parent 9dd03ee commit 30e6614
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
3 changes: 2 additions & 1 deletion examples/fastapi/frontend.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


def init(fastapi_app: FastAPI) -> None:
@ui.page('/show')
@ui.page('/')
def show():
ui.label('Hello, FastAPI!')

Expand All @@ -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
)
15 changes: 14 additions & 1 deletion nicegui/nicegui.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down

0 comments on commit 30e6614

Please sign in to comment.