16
16
from .context import get_slot_stack
17
17
from .logging import log
18
18
19
- request_contextvar : contextvars .ContextVar [Optional [Request ]] = contextvars .ContextVar (
20
- 'request_var' , default = None )
19
+ request_contextvar : contextvars .ContextVar [Optional [Request ]] = contextvars .ContextVar ('request_var' , default = None )
21
20
22
21
23
22
class ReadOnlyDict (MutableMapping ):
24
23
25
- def __init__ (self , data : Dict [Any , Any ],
26
- write_error_message : str = 'Read-only dict' ) -> None :
24
+ def __init__ (self , data : Dict [Any , Any ], write_error_message : str = 'Read-only dict' ) -> None :
27
25
self ._data : Dict [Any , Any ] = data
28
26
self ._write_error_message : str = write_error_message
29
27
@@ -65,7 +63,6 @@ def backup(self) -> None:
65
63
async def backup () -> None :
66
64
async with aiofiles .open (self .filepath , 'w' , encoding = self .encoding ) as f :
67
65
await f .write (json .dumps (self ))
68
-
69
66
if core .loop :
70
67
background_tasks .create_lazy (backup (), name = self .filepath .stem )
71
68
else :
@@ -74,8 +71,7 @@ async def backup() -> None:
74
71
75
72
class RequestTrackingMiddleware (BaseHTTPMiddleware ):
76
73
77
- async def dispatch (self , request : Request ,
78
- call_next : RequestResponseEndpoint ) -> Response :
74
+ async def dispatch (self , request : Request , call_next : RequestResponseEndpoint ) -> Response :
79
75
request_contextvar .set (request )
80
76
if 'id' not in request .session :
81
77
request .session ['id' ] = str (uuid .uuid4 ())
@@ -100,8 +96,7 @@ class Storage:
100
96
def __init__ (self ) -> None :
101
97
self .path = Path (os .environ .get ('NICEGUI_STORAGE_PATH' , '.nicegui' )).resolve ()
102
98
self .migrate_to_utf8 ()
103
- self ._general = PersistentDict (self .path / 'storage-general.json' ,
104
- encoding = 'utf-8' )
99
+ self ._general = PersistentDict (self .path / 'storage-general.json' , encoding = 'utf-8' )
105
100
self ._users : Dict [str , PersistentDict ] = {}
106
101
107
102
@property
@@ -115,11 +110,9 @@ def browser(self) -> Union[ReadOnlyDict, Dict]:
115
110
request : Optional [Request ] = request_contextvar .get ()
116
111
if request is None :
117
112
if self ._is_in_auto_index_context ():
118
- raise RuntimeError (
119
- 'app.storage.browser can only be used with page builder functions '
120
- '(https://nicegui.io/documentation/page)' )
121
- raise RuntimeError (
122
- 'app.storage.browser needs a storage_secret passed in ui.run()' )
113
+ raise RuntimeError ('app.storage.browser can only be used with page builder functions '
114
+ '(https://nicegui.io/documentation/page)' )
115
+ raise RuntimeError ('app.storage.browser needs a storage_secret passed in ui.run()' )
123
116
if request .state .responded :
124
117
return ReadOnlyDict (
125
118
request .session ,
@@ -137,27 +130,14 @@ def user(self) -> Dict:
137
130
request : Optional [Request ] = request_contextvar .get ()
138
131
if request is None :
139
132
if self ._is_in_auto_index_context ():
140
- raise RuntimeError (
141
- 'app.storage.user can only be used with page builder functions '
142
- '(https://nicegui.io/documentation/page)' )
143
- raise RuntimeError (
144
- 'app.storage.user needs a storage_secret passed in ui.run()' )
133
+ raise RuntimeError ('app.storage.user can only be used with page builder functions '
134
+ '(https://nicegui.io/documentation/page)' )
135
+ raise RuntimeError ('app.storage.user needs a storage_secret passed in ui.run()' )
145
136
session_id = request .session ['id' ]
146
137
if session_id not in self ._users :
147
- self ._users [session_id ] = PersistentDict (
148
- self .path / f'storage-user-{ session_id } .json' , encoding = 'utf-8' )
138
+ self ._users [session_id ] = PersistentDict (self .path / f'storage-user-{ session_id } .json' , encoding = 'utf-8' )
149
139
return self ._users [session_id ]
150
140
151
- @property
152
- def session (self ) -> Dict :
153
- """Volatile client storage that is persisted on the server (where NiceGUI is
154
- executed) on a per client/per connection basis.
155
-
156
- Note that this kind of storage can only be used in single page applications
157
- where the client connection is preserved between page changes."""
158
- client = context .get_client ()
159
- return client .state
160
-
161
141
@staticmethod
162
142
def _is_in_auto_index_context () -> bool :
163
143
try :
@@ -170,6 +150,15 @@ def general(self) -> Dict:
170
150
"""General storage shared between all users that is persisted on the server (where NiceGUI is executed)."""
171
151
return self ._general
172
152
153
+ @property
154
+ def session (self ) -> Dict :
155
+ """Volatile client storage that is persisted on the server (where NiceGUI is
156
+ executed) on a per client/per connection basis.
157
+ Note that this kind of storage can only be used in single page applications
158
+ where the client connection is preserved between page changes."""
159
+ client = context .get_client ()
160
+ return client .state
161
+
173
162
def clear (self ) -> None :
174
163
"""Clears all storage."""
175
164
self ._general .clear ()
@@ -192,4 +181,4 @@ def migrate_to_utf8(self) -> None:
192
181
log .warning (f'Could not load storage file { filepath } ' )
193
182
data = {}
194
183
filepath .rename (new_filepath )
195
- new_filepath .write_text (json .dumps (data ), encoding = 'utf-8' )
184
+ new_filepath .write_text (json .dumps (data ), encoding = 'utf-8' )
0 commit comments