浏览代码

Add request object to the client (#3286)

* make client.ip available even before client.connected
(part of #1727)

* pass request object in Client constructor

* add ip test and fixed "reset_globals"

* code review

* revert changes to `client.ip`

---------

Co-authored-by: Rodja Trappe <rodja@zauberzeug.com>
Falko Schindler 10 月之前
父节点
当前提交
9c54fbe004

+ 3 - 2
nicegui/client.py

@@ -46,7 +46,8 @@ class Client:
     shared_body_html = ''
     """HTML to be inserted in the <body> of every page template."""
 
-    def __init__(self, page: page, *, shared: bool = False) -> None:
+    def __init__(self, page: page, *, request: Optional[Request]) -> None:
+        self.request: Optional[Request] = request
         self.id = str(uuid.uuid4())
         self.created = time.time()
         self.instances[self.id] = self
@@ -56,7 +57,7 @@ class Client:
         self.is_waiting_for_connection: bool = False
         self.is_waiting_for_disconnect: bool = False
         self.environ: Optional[Dict[str, Any]] = None
-        self.shared = shared
+        self.shared = request is None
         self.on_air = False
         self._disconnect_task: Optional[asyncio.Task] = None
         self._deleted = False

+ 3 - 3
nicegui/nicegui.py

@@ -62,7 +62,7 @@ static_files = StaticFiles(
 )
 app.mount(f'/_nicegui/{__version__}/static', static_files, name='static')
 
-Client.auto_index_client = Client(page('/'), shared=True).__enter__()  # pylint: disable=unnecessary-dunder-call
+Client.auto_index_client = Client(page('/'), request=None).__enter__()  # pylint: disable=unnecessary-dunder-call
 
 
 @app.get('/')
@@ -149,7 +149,7 @@ async def _shutdown() -> None:
 @app.exception_handler(404)
 async def _exception_handler_404(request: Request, exception: Exception) -> Response:
     log.warning(f'{request.url} not found')
-    with Client(page('')) as client:
+    with Client(page(''), request=request) as client:
         error_content(404, exception)
     return client.build_response(request, 404)
 
@@ -157,7 +157,7 @@ async def _exception_handler_404(request: Request, exception: Exception) -> Resp
 @app.exception_handler(Exception)
 async def _exception_handler_500(request: Request, exception: Exception) -> Response:
     log.exception(exception)
-    with Client(page('')) as client:
+    with Client(page(''), request=request) as client:
         error_content(500, exception)
     return client.build_response(request, 500)
 

+ 1 - 1
nicegui/page.py

@@ -102,7 +102,7 @@ class page:
             request = dec_kwargs['request']
             # NOTE cleaning up the keyword args so the signature is consistent with "func" again
             dec_kwargs = {k: v for k, v in dec_kwargs.items() if k in parameters_of_decorated_func}
-            with Client(self) as client:
+            with Client(self, request=request) as client:
                 if any(p.name == 'client' for p in inspect.signature(func).parameters.values()):
                     dec_kwargs['client'] = client
                 result = func(*dec_args, **dec_kwargs)

+ 1 - 1
nicegui/testing/conftest.py

@@ -70,7 +70,7 @@ def reset_globals() -> Generator[None, None, None]:
     Client.instances.clear()
     Client.page_routes.clear()
     app.reset()
-    Client.auto_index_client = Client(page('/'), shared=True).__enter__()  # pylint: disable=unnecessary-dunder-call
+    Client.auto_index_client = Client(page('/'), request=None).__enter__()  # pylint: disable=unnecessary-dunder-call
     # NOTE we need to re-add the auto index route because we removed all routes above
     app.get('/')(Client.auto_index_client.build_response)
     binding.reset()

+ 2 - 2
website/documentation/content/section_configuration_deployment.py

@@ -148,8 +148,8 @@ def uvicorn_ssl():
             from nicegui import ui
 
             ui.run(
-                port=443, 
-                ssl_certfile="<path_to_certfile>", 
+                port=443,
+                ssl_certfile="<path_to_certfile>",
                 ssl_keyfile="<path_to_keyfile>",
             )
             ```