storage.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import contextvars
  2. import os
  3. import uuid
  4. from collections.abc import MutableMapping
  5. from pathlib import Path
  6. from typing import Any, Dict, Iterator, Optional, Union
  7. import aiofiles
  8. from starlette.middleware import Middleware
  9. from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
  10. from starlette.middleware.sessions import SessionMiddleware
  11. from starlette.requests import Request
  12. from starlette.responses import Response
  13. from . import background_tasks, context, core, json, observables
  14. from .logging import log
  15. request_contextvar: contextvars.ContextVar[Optional[Request]] = contextvars.ContextVar('request_var', default=None)
  16. class ReadOnlyDict(MutableMapping):
  17. def __init__(self, data: Dict[Any, Any], write_error_message: str = 'Read-only dict') -> None:
  18. self._data: Dict[Any, Any] = data
  19. self._write_error_message: str = write_error_message
  20. def __getitem__(self, item: Any) -> Any:
  21. return self._data[item]
  22. def __setitem__(self, key: Any, value: Any) -> None:
  23. raise TypeError(self._write_error_message)
  24. def __delitem__(self, key: Any) -> None:
  25. raise TypeError(self._write_error_message)
  26. def __iter__(self) -> Iterator:
  27. return iter(self._data)
  28. def __len__(self) -> int:
  29. return len(self._data)
  30. class PersistentDict(observables.ObservableDict):
  31. def __init__(self, filepath: Path, encoding: Optional[str] = None) -> None:
  32. self.filepath = filepath
  33. self.encoding = encoding
  34. try:
  35. data = json.loads(filepath.read_text(encoding)) if filepath.exists() else {}
  36. except Exception:
  37. log.warning(f'Could not load storage file {filepath}')
  38. data = {}
  39. super().__init__(data, on_change=self.backup)
  40. def backup(self) -> None:
  41. """Back up the data to the given file path."""
  42. if not self.filepath.exists():
  43. if not self:
  44. return
  45. self.filepath.parent.mkdir(exist_ok=True)
  46. async def backup() -> None:
  47. async with aiofiles.open(self.filepath, 'w', encoding=self.encoding) as f:
  48. await f.write(json.dumps(self))
  49. if core.loop:
  50. background_tasks.create_lazy(backup(), name=self.filepath.stem)
  51. else:
  52. core.app.on_startup(backup())
  53. class RequestTrackingMiddleware(BaseHTTPMiddleware):
  54. async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
  55. request_contextvar.set(request)
  56. if 'id' not in request.session:
  57. request.session['id'] = str(uuid.uuid4())
  58. request.state.responded = False
  59. response = await call_next(request)
  60. request.state.responded = True
  61. return response
  62. def set_storage_secret(storage_secret: Optional[str] = None) -> None:
  63. """Set storage_secret and add request tracking middleware."""
  64. if any(m.cls == SessionMiddleware for m in core.app.user_middleware):
  65. # NOTE not using "add_middleware" because it would be the wrong order
  66. core.app.user_middleware.append(Middleware(RequestTrackingMiddleware))
  67. elif storage_secret is not None:
  68. core.app.add_middleware(RequestTrackingMiddleware)
  69. core.app.add_middleware(SessionMiddleware, secret_key=storage_secret)
  70. class Storage:
  71. def __init__(self) -> None:
  72. self.path = Path(os.environ.get('NICEGUI_STORAGE_PATH', '.nicegui')).resolve()
  73. self.migrate_to_utf8()
  74. self._general = PersistentDict(self.path / 'storage-general.json', encoding='utf-8')
  75. self._users: Dict[str, PersistentDict] = {}
  76. @property
  77. def browser(self) -> Union[ReadOnlyDict, Dict]:
  78. """Small storage that is saved directly within the user's browser (encrypted cookie).
  79. The data is shared between all browser tabs and can only be modified before the initial request has been submitted.
  80. Therefore it is normally better to use `app.storage.user` instead,
  81. which can be modified anytime, reduces overall payload, improves security and has larger storage capacity.
  82. """
  83. request: Optional[Request] = request_contextvar.get()
  84. if request is None:
  85. if context.get_client().is_auto_index_client:
  86. raise RuntimeError('app.storage.browser can only be used with page builder functions '
  87. '(https://nicegui.io/documentation/page)')
  88. raise RuntimeError('app.storage.browser needs a storage_secret passed in ui.run()')
  89. if request.state.responded:
  90. return ReadOnlyDict(
  91. request.session,
  92. 'the response to the browser has already been built, so modifications cannot be sent back anymore'
  93. )
  94. return request.session
  95. @property
  96. def user(self) -> Dict:
  97. """Individual user storage that is persisted on the server (where NiceGUI is executed).
  98. The data is stored in a file on the server.
  99. It is shared between all browser tabs by identifying the user via session cookie ID.
  100. """
  101. request: Optional[Request] = request_contextvar.get()
  102. if request is None:
  103. try:
  104. if context.get_client().is_auto_index_client:
  105. raise RuntimeError('app.storage.user can only be used with page builder functions '
  106. '(https://nicegui.io/documentation/page)')
  107. except RuntimeError:
  108. pass # no storage_secret (see #2438)
  109. raise RuntimeError('app.storage.user needs a storage_secret passed in ui.run()')
  110. session_id = request.session['id']
  111. if session_id not in self._users:
  112. self._users[session_id] = PersistentDict(self.path / f'storage-user-{session_id}.json', encoding='utf-8')
  113. return self._users[session_id]
  114. @property
  115. def general(self) -> Dict:
  116. """General storage shared between all users that is persisted on the server (where NiceGUI is executed)."""
  117. return self._general
  118. def clear(self) -> None:
  119. """Clears all storage."""
  120. self._general.clear()
  121. self._users.clear()
  122. for filepath in self.path.glob('storage-*.json'):
  123. filepath.unlink()
  124. def migrate_to_utf8(self) -> None:
  125. """Migrates storage files from system's default encoding to UTF-8.
  126. To distinguish between the old and new encoding, the new files are named with dashes instead of underscores.
  127. """
  128. for filepath in self.path.glob('storage_*.json'):
  129. new_filepath = filepath.with_name(filepath.name.replace('_', '-'))
  130. try:
  131. data = json.loads(filepath.read_text())
  132. except Exception:
  133. log.warning(f'Could not load storage file {filepath}')
  134. data = {}
  135. filepath.rename(new_filepath)
  136. new_filepath.write_text(json.dumps(data), encoding='utf-8')