globals.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. tasks: List[asyncio.tasks.Task] = []
  36. startup_handlers: List[Union[Callable, Awaitable]] = []
  37. shutdown_handlers: List[Union[Callable, Awaitable]] = []
  38. def get_task_id() -> int:
  39. try:
  40. return id(asyncio.current_task())
  41. except RuntimeError:
  42. return 0
  43. def get_slot_stack() -> List['Slot']:
  44. task_id = get_task_id()
  45. if task_id not in slot_stacks:
  46. slot_stacks[task_id] = []
  47. return slot_stacks[task_id]
  48. def prune_slot_stack() -> None:
  49. task_id = get_task_id()
  50. if not slot_stacks[task_id]:
  51. del slot_stacks[task_id]
  52. def get_slot() -> 'Slot':
  53. return get_slot_stack()[-1]
  54. def get_client() -> 'Client':
  55. return get_slot().parent.client