Prechádzať zdrojové kódy

Merge pull request #2521 from zauberzeug/sio-root-path

Strip root_path to make ASGIServer from socketio compatible with mounting as sub-app
Falko Schindler 1 rok pred
rodič
commit
dc7e8059e5
2 zmenil súbory, kde vykonal 17 pridanie a 2 odobranie
  1. 2 1
      examples/fastapi/frontend.py
  2. 15 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:
-    @ui.page('/show')
+    @ui.page('/')
     def show():
         ui.label('Hello, FastAPI!')
 
@@ -14,5 +14,6 @@ def init(fastapi_app: FastAPI) -> None:
 
     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 - 1
nicegui/nicegui.py

@@ -30,10 +30,24 @@ async def _lifespan(_: App):
     yield
     await _shutdown()
 
+
+class SocketIoApp(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):
+        root_path = scope.get('root_path')
+        if root_path and scope['path'].startswith(root_path):
+            scope['path'] = scope['path'][len(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 = SocketIoApp(socketio_server=sio, socketio_path='/socket.io')
 app.mount('/_nicegui_ws/', sio_app)