Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
keep single-use routes for a few seconds before pruning them
Browse files Browse the repository at this point in the history
falkoschindler committed Jan 14, 2025
1 parent 87cba75 commit 0c4407c
Showing 2 changed files with 15 additions and 2 deletions.
16 changes: 14 additions & 2 deletions nicegui/app/app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import asyncio
import inspect
import os
import platform
import signal
import time
import urllib
from enum import Enum
from pathlib import Path
@@ -39,6 +41,7 @@ def __init__(self, **kwargs) -> None:
self.urls = ObservableSet()
self._state: State = State.STOPPED
self.config = AppConfig()
self._routes_to_remove: dict[str, float] = {}

self._startup_handlers: List[Union[Callable[..., Any], Awaitable]] = []
self._shutdown_handlers: List[Union[Callable[..., Any], Awaitable]] = []
@@ -202,7 +205,7 @@ def add_static_file(self, *,
@self.get(path)
def read_item() -> FileResponse:
if single_use:
self.remove_route(path)
self._routes_to_remove[path] = time.time() + 10.0
return FileResponse(file, headers={'Cache-Control': f'public, max-age={max_cache_age}'})

return urllib.parse.quote(path)
@@ -254,7 +257,7 @@ def add_media_file(self, *,
@self.get(path)
def read_item(request: Request, nicegui_chunk_size: int = 8192) -> Response:
if single_use:
self.remove_route(path)
self._routes_to_remove[path] = time.time() + 10.0
return get_range_response(file, request, chunk_size=nicegui_chunk_size)

return urllib.parse.quote(path)
@@ -284,3 +287,12 @@ def clients(path: str) -> Iterator[Client]:
for client in Client.instances.values():
if client.page.path == path:
yield client

async def prune_single_use_routes(self) -> None:
"""Prune single-use routes."""
while True:
routes = [path for path, timestamp in self._routes_to_remove.items() if time.time() > timestamp]
for path in routes:
self.remove_route(path)
del self._routes_to_remove[path]
await asyncio.sleep(10.0)
1 change: 1 addition & 0 deletions nicegui/nicegui.py
Original file line number Diff line number Diff line change
@@ -129,6 +129,7 @@ async def _startup() -> None:
background_tasks.create(binding.refresh_loop(), name='refresh bindings')
background_tasks.create(Client.prune_instances(), name='prune clients')
background_tasks.create(Slot.prune_stacks(), name='prune slot stacks')
background_tasks.create(core.app.prune_single_use_routes(), name='prune single-use routes')
background_tasks.create(core.app.storage.prune_tab_storage(), name='prune tab storage')
air.connect()

0 comments on commit 0c4407c

Please sign in to comment.