globals.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import asyncio
  2. import logging
  3. from enum import Enum
  4. from typing import TYPE_CHECKING, Awaitable, Callable, Dict, List, Optional, Union
  5. from fastapi import FastAPI
  6. from socketio import AsyncServer
  7. from uvicorn import Server
  8. if TYPE_CHECKING:
  9. from .client import Client
  10. from .slot import Slot
  11. class State(Enum):
  12. STOPPED = 0
  13. STARTING = 1
  14. STARTED = 2
  15. STOPPING = 3
  16. app: FastAPI
  17. sio: AsyncServer
  18. server: Server
  19. loop: Optional[asyncio.AbstractEventLoop] = None
  20. log: logging.Logger = logging.getLogger('nicegui')
  21. state: State = State.STOPPED
  22. host: str
  23. port: int
  24. reload: bool
  25. title: str
  26. favicon: Optional[str]
  27. dark: Optional[bool]
  28. binding_refresh_interval: float
  29. excludes: List[str]
  30. socket_io_js_extra_headers: Dict = {}
  31. slot_stacks: Dict[int, List['Slot']] = {}
  32. clients: Dict[str, 'Client'] = {}
  33. index_client: 'Client'
  34. page_routes: Dict[Callable, str] = {}
  35. favicons: Dict[str, Optional[str]] = {}
  36. tasks: List[asyncio.tasks.Task] = []
  37. startup_handlers: List[Union[Callable, Awaitable]] = []
  38. shutdown_handlers: List[Union[Callable, Awaitable]] = []
  39. def get_task_id() -> int:
  40. try:
  41. return id(asyncio.current_task())
  42. except RuntimeError:
  43. return 0
  44. def get_slot_stack() -> List['Slot']:
  45. task_id = get_task_id()
  46. if task_id not in slot_stacks:
  47. slot_stacks[task_id] = []
  48. return slot_stacks[task_id]
  49. def prune_slot_stack() -> None:
  50. task_id = get_task_id()
  51. if not slot_stacks[task_id]:
  52. del slot_stacks[task_id]
  53. def get_slot() -> 'Slot':
  54. return get_slot_stack()[-1]
  55. def get_client() -> 'Client':
  56. return get_slot().parent.client