storage.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import contextvars
  2. import json
  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.base import BaseHTTPMiddleware, RequestResponseEndpoint
  9. from starlette.requests import Request
  10. from starlette.responses import Response
  11. from . import background_tasks, globals, observables # pylint: disable=redefined-builtin
  12. request_contextvar: contextvars.ContextVar[Optional[Request]] = contextvars.ContextVar('request_var', default=None)
  13. class ReadOnlyDict(MutableMapping):
  14. def __init__(self, data: Dict[Any, Any], write_error_message: str = 'Read-only dict') -> None:
  15. self._data: Dict[Any, Any] = data
  16. self._write_error_message: str = write_error_message
  17. def __getitem__(self, item: Any) -> Any:
  18. return self._data[item]
  19. def __setitem__(self, key: Any, value: Any) -> None:
  20. raise TypeError(self._write_error_message)
  21. def __delitem__(self, key: Any) -> None:
  22. raise TypeError(self._write_error_message)
  23. def __iter__(self) -> Iterator:
  24. return iter(self._data)
  25. def __len__(self) -> int:
  26. return len(self._data)
  27. class PersistentDict(observables.ObservableDict):
  28. def __init__(self, filepath: Path) -> None:
  29. self.filepath = filepath
  30. data = json.loads(filepath.read_text()) if filepath.exists() else {}
  31. super().__init__(data, on_change=self.backup)
  32. def backup(self) -> None:
  33. if not self.filepath.exists():
  34. if not self:
  35. return
  36. self.filepath.parent.mkdir(exist_ok=True)
  37. async def backup() -> None:
  38. async with aiofiles.open(self.filepath, 'w') as f:
  39. await f.write(json.dumps(self))
  40. if globals.loop:
  41. background_tasks.create_lazy(backup(), name=self.filepath.stem)
  42. else:
  43. globals.app.on_startup(backup())
  44. class RequestTrackingMiddleware(BaseHTTPMiddleware):
  45. async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
  46. request_contextvar.set(request)
  47. if 'id' not in request.session:
  48. request.session['id'] = str(uuid.uuid4())
  49. request.state.responded = False
  50. response = await call_next(request)
  51. request.state.responded = True
  52. return response
  53. class Storage:
  54. def __init__(self) -> None:
  55. self._general = PersistentDict(globals.storage_path / 'storage_general.json')
  56. self._users: Dict[str, PersistentDict] = {}
  57. @property
  58. def browser(self) -> Union[ReadOnlyDict, Dict]:
  59. """Small storage that is saved directly within the user's browser (encrypted cookie).
  60. The data is shared between all browser tabs and can only be modified before the initial request has been submitted.
  61. Therefore it is normally better to use `app.storage.user` instead,
  62. which can be modified anytime, reduces overall payload, improves security and has larger storage capacity.
  63. """
  64. request: Optional[Request] = request_contextvar.get()
  65. if request is None:
  66. if globals.get_client() == globals.index_client:
  67. raise RuntimeError('app.storage.browser can only be used with page builder functions '
  68. '(https://nicegui.io/documentation/page)')
  69. raise RuntimeError('app.storage.browser needs a storage_secret passed in ui.run()')
  70. if request.state.responded:
  71. return ReadOnlyDict(
  72. request.session,
  73. 'the response to the browser has already been built, so modifications cannot be sent back anymore'
  74. )
  75. return request.session
  76. @property
  77. def user(self) -> Dict:
  78. """Individual user storage that is persisted on the server (where NiceGUI is executed).
  79. The data is stored in a file on the server.
  80. It is shared between all browser tabs by identifying the user via session cookie ID.
  81. """
  82. request: Optional[Request] = request_contextvar.get()
  83. if request is None:
  84. if globals.get_client() == globals.index_client:
  85. raise RuntimeError('app.storage.user can only be used with page builder functions '
  86. '(https://nicegui.io/documentation/page)')
  87. raise RuntimeError('app.storage.user needs a storage_secret passed in ui.run()')
  88. session_id = request.session['id']
  89. if session_id not in self._users:
  90. self._users[session_id] = PersistentDict(globals.storage_path / f'storage_user_{session_id}.json')
  91. return self._users[session_id]
  92. @property
  93. def general(self) -> Dict:
  94. """General storage shared between all users that is persisted on the server (where NiceGUI is executed)."""
  95. return self._general
  96. def clear(self) -> None:
  97. """Clears all storage."""
  98. self._general.clear()
  99. self._users.clear()
  100. for filepath in globals.storage_path.glob('storage_*.json'):
  101. filepath.unlink()