page.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import asyncio
  2. import inspect
  3. import time
  4. from pathlib import Path
  5. from typing import TYPE_CHECKING, Any, Callable, Optional, Union
  6. from fastapi import Request, Response
  7. from . import background_tasks, globals
  8. from .client import Client
  9. from .favicon import create_favicon_route
  10. from .language import Language
  11. if TYPE_CHECKING:
  12. from .api_router import APIRouter
  13. class page:
  14. def __init__(self,
  15. path: str, *,
  16. title: Optional[str] = None,
  17. viewport: Optional[str] = None,
  18. favicon: Optional[Union[str, Path]] = None,
  19. dark: Optional[bool] = ...,
  20. language: Language = ...,
  21. response_timeout: float = 3.0,
  22. api_router: Optional['APIRouter'] = None,
  23. **kwargs: Any,
  24. ) -> None:
  25. """Page
  26. This decorator marks a function to be a page builder.
  27. Each user accessing the given route will see a new instance of the page.
  28. This means it is private to the user and not shared with others
  29. (as it is done `when placing elements outside of a page decorator <https://nicegui.io/documentation#auto-index_page>`_).
  30. :param path: route of the new page (path must start with '/')
  31. :param title: optional page title
  32. :param viewport: optional viewport meta tag content
  33. :param favicon: optional relative filepath or absolute URL to a favicon (default: `None`, NiceGUI icon will be used)
  34. :param dark: whether to use Quasar's dark mode (defaults to `dark` argument of `run` command)
  35. :param language: language of the page (defaults to `language` argument of `run` command)
  36. :param response_timeout: maximum time for the decorated function to build the page (default: 3.0)
  37. :param api_router: APIRouter instance to use, can be left `None` to use the default
  38. :param kwargs: additional keyword arguments passed to FastAPI's @app.get method
  39. """
  40. self._path = path
  41. self.title = title
  42. self.viewport = viewport
  43. self.favicon = favicon
  44. self.dark = dark
  45. self.language = language
  46. self.response_timeout = response_timeout
  47. self.kwargs = kwargs
  48. self.api_router = api_router or globals.app.router
  49. create_favicon_route(self.path, favicon)
  50. @property
  51. def path(self) -> str:
  52. return self.api_router.prefix + self._path
  53. def resolve_title(self) -> str:
  54. return self.title if self.title is not None else globals.title
  55. def resolve_viewport(self) -> str:
  56. return self.viewport if self.viewport is not None else globals.viewport
  57. def resolve_dark(self) -> Optional[bool]:
  58. return self.dark if self.dark is not ... else globals.dark
  59. def resolve_language(self) -> Optional[str]:
  60. return self.language if self.language is not ... else globals.language
  61. def __call__(self, func: Callable[..., Any]) -> Callable[..., Any]:
  62. globals.app.remove_route(self.path) # NOTE make sure only the latest route definition is used
  63. parameters_of_decorated_func = list(inspect.signature(func).parameters.keys())
  64. async def decorated(*dec_args, **dec_kwargs) -> Response:
  65. request = dec_kwargs['request']
  66. # NOTE cleaning up the keyword args so the signature is consistent with "func" again
  67. dec_kwargs = {k: v for k, v in dec_kwargs.items() if k in parameters_of_decorated_func}
  68. with Client(self) as client:
  69. if any(p.name == 'client' for p in inspect.signature(func).parameters.values()):
  70. dec_kwargs['client'] = client
  71. result = func(*dec_args, **dec_kwargs)
  72. if inspect.isawaitable(result):
  73. async def wait_for_result() -> None:
  74. with client:
  75. return await result
  76. task = background_tasks.create(wait_for_result())
  77. deadline = time.time() + self.response_timeout
  78. while task and not client.is_waiting_for_connection and not task.done():
  79. if time.time() > deadline:
  80. raise TimeoutError(f'Response not ready after {self.response_timeout} seconds')
  81. await asyncio.sleep(0.1)
  82. result = task.result() if task.done() else None
  83. if isinstance(result, Response): # NOTE if setup returns a response, we don't need to render the page
  84. return result
  85. return client.build_response(request)
  86. parameters = [p for p in inspect.signature(func).parameters.values() if p.name != 'client']
  87. # NOTE adding request as a parameter so we can pass it to the client in the decorated function
  88. if 'request' not in {p.name for p in parameters}:
  89. request = inspect.Parameter('request', inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Request)
  90. parameters.insert(0, request)
  91. decorated.__signature__ = inspect.Signature(parameters)
  92. show_in_docs = False
  93. if globals.endpoint_documentation in ['page', 'all']:
  94. show_in_docs = True
  95. self.kwargs['include_in_schema'] = show_in_docs
  96. self.api_router.get(self._path, **self.kwargs)(decorated)
  97. globals.page_routes[func] = self.path
  98. return func