Преглед на файлове

strip root_path to make ASGIServer from socketio compatible with mounting as sub-app (fixes #2468 and #2515)

Rodja Trappe преди 1 година
родител
ревизия
30e66144ce
променени са 2 файла, в които са добавени 16 реда и са изтрити 2 реда
  1. 2 1
      examples/fastapi/frontend.py
  2. 14 1
      nicegui/nicegui.py

+ 2 - 1
examples/fastapi/frontend.py

@@ -4,7 +4,7 @@ from nicegui import app, ui
 
 
 
 
 def init(fastapi_app: FastAPI) -> None:
 def init(fastapi_app: FastAPI) -> None:
-    @ui.page('/show')
+    @ui.page('/')
     def show():
     def show():
         ui.label('Hello, FastAPI!')
         ui.label('Hello, FastAPI!')
 
 
@@ -14,5 +14,6 @@ def init(fastapi_app: FastAPI) -> None:
 
 
     ui.run_with(
     ui.run_with(
         fastapi_app,
         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
         storage_secret='pick your private secret here',  # NOTE setting a secret is optional but allows for persistent storage per user
     )
     )

+ 14 - 1
nicegui/nicegui.py

@@ -30,10 +30,23 @@ async def _lifespan(_: App):
     yield
     yield
     await _shutdown()
     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)
 core.app = app = App(default_response_class=NiceGUIJSONResponse, lifespan=_lifespan)
 # NOTE we use custom json module which wraps orjson
 # NOTE we use custom json module which wraps orjson
 core.sio = sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins='*', json=json)
 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)
 app.mount('/_nicegui_ws/', sio_app)