瀏覽代碼

rename app.storage.individual to app.storage.user

Rodja Trappe 2 年之前
父節點
當前提交
ab6aeae5c4
共有 4 個文件被更改,包括 33 次插入33 次删除
  1. 5 5
      examples/authentication/main.py
  2. 8 8
      nicegui/storage.py
  3. 1 1
      tests/conftest.py
  4. 19 19
      tests/test_storage.py

+ 5 - 5
examples/authentication/main.py

@@ -16,11 +16,11 @@ users = [('user1', 'pass1'), ('user2', 'pass2')]
 
 
 @ui.page('/')
 @ui.page('/')
 def main_page() -> None:
 def main_page() -> None:
-    if not app.storage.individual.get('authenticated', False):
+    if not app.storage.user.get('authenticated', False):
         return RedirectResponse('/login')
         return RedirectResponse('/login')
     with ui.column().classes('absolute-center items-center'):
     with ui.column().classes('absolute-center items-center'):
-        ui.label(f'Hello {app.storage.individual["username"]}!').classes('text-2xl')
-        ui.button('', on_click=lambda: (app.storage.individual.clear(), ui.open('/login'))) \
+        ui.label(f'Hello {app.storage.user["username"]}!').classes('text-2xl')
+        ui.button('', on_click=lambda: (app.storage.user.clear(), ui.open('/login'))) \
             .props('outline round icon=logout')
             .props('outline round icon=logout')
 
 
 
 
@@ -28,12 +28,12 @@ def main_page() -> None:
 def login() -> None:
 def login() -> None:
     def try_login() -> None:  # local function to avoid passing username and password as arguments
     def try_login() -> None:  # local function to avoid passing username and password as arguments
         if (username.value, password.value) in users:
         if (username.value, password.value) in users:
-            app.storage.individual.update({'username': username.value, 'authenticated': True})
+            app.storage.user.update({'username': username.value, 'authenticated': True})
             ui.open('/')
             ui.open('/')
         else:
         else:
             ui.notify('Wrong username or password', color='negative')
             ui.notify('Wrong username or password', color='negative')
 
 
-    if app.storage.individual.get('authenticated', False):
+    if app.storage.user.get('authenticated', False):
         return RedirectResponse('/')
         return RedirectResponse('/')
     with ui.card().classes('absolute-center'):
     with ui.card().classes('absolute-center'):
         username = ui.input('Username').on('keydown.enter', try_login)
         username = ui.input('Username').on('keydown.enter', try_login)

+ 8 - 8
nicegui/storage.py

@@ -87,14 +87,14 @@ class Storage:
         self.storage_dir = Path('.nicegui')
         self.storage_dir = Path('.nicegui')
         self.storage_dir.mkdir(exist_ok=True)
         self.storage_dir.mkdir(exist_ok=True)
         self._general = PersistentDict(self.storage_dir / 'storage_general.json')
         self._general = PersistentDict(self.storage_dir / 'storage_general.json')
-        self._individuals = PersistentDict(self.storage_dir / 'storage_individuals.json')
+        self._users = PersistentDict(self.storage_dir / 'storage_users.json')
 
 
     @property
     @property
     def browser(self) -> Dict:
     def browser(self) -> Dict:
         """Small storage that is saved directly within the user's browser (encrypted cookie).
         """Small storage that is saved directly within the user's browser (encrypted cookie).
 
 
         The data is shared between all browser tab and can only be modified before the initial request has been submitted.
         The data is shared between all browser tab and can only be modified before the initial request has been submitted.
-        Normally it is better to use `app.storage.individual` instead to reduce payload, improved security and larger storage capacity)."""
+        Normally it is better to use `app.storage.user` instead to reduce payload, improved security and larger storage capacity)."""
         request: Request = request_contextvar.get()
         request: Request = request_contextvar.get()
         if request is None:
         if request is None:
             raise RuntimeError('storage.browser needs a storage_secret passed in ui.run()')
             raise RuntimeError('storage.browser needs a storage_secret passed in ui.run()')
@@ -106,7 +106,7 @@ class Storage:
         return request.session
         return request.session
 
 
     @property
     @property
-    def individual(self) -> Dict:
+    def user(self) -> Dict:
         """Individual user storage that is persisted on the server (where NiceGUI is executed).
         """Individual user storage that is persisted on the server (where NiceGUI is executed).
 
 
         The data is stored in a file on the server.
         The data is stored in a file on the server.
@@ -114,10 +114,10 @@ class Storage:
         """
         """
         request: Request = request_contextvar.get()
         request: Request = request_contextvar.get()
         if request is None:
         if request is None:
-            raise RuntimeError('storage.individual needs a storage_secret passed in ui.run()')
-        if request.session['id'] not in self._individuals:
-            self._individuals[request.session['id']] = {}
-        return self._individuals[request.session['id']]
+            raise RuntimeError('app.storage.user needs a storage_secret passed in ui.run()')
+        if request.session['id'] not in self._users:
+            self._users[request.session['id']] = {}
+        return self._users[request.session['id']]
 
 
     @property
     @property
     def general(self) -> Dict:
     def general(self) -> Dict:
@@ -126,7 +126,7 @@ class Storage:
 
 
     async def backup(self):
     async def backup(self):
         await self._general.backup()
         await self._general.backup()
-        await self._individuals.backup()
+        await self._users.backup()
 
 
     async def _loop(self):
     async def _loop(self):
         while True:
         while True:

+ 1 - 1
tests/conftest.py

@@ -43,7 +43,7 @@ def reset_globals() -> Generator[None, None, None]:
     importlib.reload(globals)
     importlib.reload(globals)
     # importlib.reload(nicegui)
     # importlib.reload(nicegui)
     globals.app.storage.general.clear()
     globals.app.storage.general.clear()
-    globals.app.storage._individuals.clear()
+    globals.app.storage._users.clear()
     globals.index_client = Client(page('/'), shared=True).__enter__()
     globals.index_client = Client(page('/'), shared=True).__enter__()
     globals.app.get('/')(globals.index_client.build_response)
     globals.app.get('/')(globals.index_client.build_response)
 
 

+ 19 - 19
tests/test_storage.py

@@ -57,13 +57,13 @@ def test_browser_storage_modifications_after_page_load_are_forbidden(screen: Scr
     screen.should_contain('response to the browser has already been build')
     screen.should_contain('response to the browser has already been build')
 
 
 
 
-def test_individual_storage_modifications(screen: Screen):
+def test_user_storage_modifications(screen: Screen):
     @ui.page('/')
     @ui.page('/')
     async def page(client: Client, delayed: bool = False):
     async def page(client: Client, delayed: bool = False):
         if delayed:
         if delayed:
             await client.connected()
             await client.connected()
-        app.storage.individual['count'] = app.storage.individual.get('count', 0) + 1
-        ui.label().bind_text_from(app.storage.individual, 'count')
+        app.storage.user['count'] = app.storage.user.get('count', 0) + 1
+        ui.label().bind_text_from(app.storage.user, 'count')
 
 
     screen.ui_run_kwargs['storage_secret'] = 'just a test'
     screen.ui_run_kwargs['storage_secret'] = 'just a test'
     screen.open('/')
     screen.open('/')
@@ -74,26 +74,26 @@ def test_individual_storage_modifications(screen: Screen):
     screen.should_contain('3')
     screen.should_contain('3')
 
 
 
 
-async def test_access_individual_storage_on_interaction(screen: Screen):
+async def test_access_user_storage_on_interaction(screen: Screen):
     @ui.page('/')
     @ui.page('/')
     async def page():
     async def page():
-        if 'test_switch' not in app.storage.individual:
-            app.storage.individual['test_switch'] = False
-        ui.switch('switch').bind_value(app.storage.individual, 'test_switch')
+        if 'test_switch' not in app.storage.user:
+            app.storage.user['test_switch'] = False
+        ui.switch('switch').bind_value(app.storage.user, 'test_switch')
 
 
     screen.ui_run_kwargs['storage_secret'] = 'just a test'
     screen.ui_run_kwargs['storage_secret'] = 'just a test'
     screen.open('/')
     screen.open('/')
     screen.click('switch')
     screen.click('switch')
     screen.wait(1)
     screen.wait(1)
     await app.storage.backup()
     await app.storage.backup()
-    assert '{"test_switch": true}' in app.storage._individuals.filename.read_text()
+    assert '{"test_switch": true}' in app.storage._users.filename.read_text()
 
 
 
 
-def test_access_individual_storage_from_button_click_handler(screen: Screen):
+def test_access_user_storage_from_button_click_handler(screen: Screen):
     @ui.page('/')
     @ui.page('/')
     async def page():
     async def page():
         async def inner():
         async def inner():
-            app.storage.individual['inner_function'] = 'works'
+            app.storage.user['inner_function'] = 'works'
             await app.storage.backup()
             await app.storage.backup()
 
 
         ui.button('test', on_click=inner)
         ui.button('test', on_click=inner)
@@ -102,29 +102,29 @@ def test_access_individual_storage_from_button_click_handler(screen: Screen):
     screen.open('/')
     screen.open('/')
     screen.click('test')
     screen.click('test')
     screen.wait(1)
     screen.wait(1)
-    assert '{"inner_function": "works"}' in app.storage._individuals.filename.read_text()
+    assert '{"inner_function": "works"}' in app.storage._users.filename.read_text()
 
 
 
 
-async def test_access_individual_storage_from_background_task(screen: Screen):
+async def test_access_user_storage_from_background_task(screen: Screen):
     @ui.page('/')
     @ui.page('/')
     def page():
     def page():
         async def subtask():
         async def subtask():
             await asyncio.sleep(0.1)
             await asyncio.sleep(0.1)
-            app.storage.individual['subtask'] = 'works'
+            app.storage.user['subtask'] = 'works'
             await app.storage.backup()
             await app.storage.backup()
         background_tasks.create(subtask())
         background_tasks.create(subtask())
 
 
     screen.ui_run_kwargs['storage_secret'] = 'just a test'
     screen.ui_run_kwargs['storage_secret'] = 'just a test'
     screen.open('/')
     screen.open('/')
-    assert '{"subtask": "works"}' in app.storage._individuals.filename.read_text()
+    assert '{"subtask": "works"}' in app.storage._users.filename.read_text()
 
 
 
 
-def test_individual_and_general_storage_is_persisted(screen: Screen):
+def test_user_and_general_storage_is_persisted(screen: Screen):
     @ui.page('/')
     @ui.page('/')
     def page():
     def page():
-        app.storage.individual['count'] = app.storage.individual.get('count', 0) + 1
+        app.storage.user['count'] = app.storage.user.get('count', 0) + 1
         app.storage.general['count'] = app.storage.general.get('count', 0) + 1
         app.storage.general['count'] = app.storage.general.get('count', 0) + 1
-        ui.label(f'individual: {app.storage.individual["count"]}')
+        ui.label(f'user: {app.storage.user["count"]}')
         ui.label(f'general: {app.storage.general["count"]}')
         ui.label(f'general: {app.storage.general["count"]}')
         ui.button('backup', on_click=app.storage.backup)
         ui.button('backup', on_click=app.storage.backup)
 
 
@@ -132,10 +132,10 @@ def test_individual_and_general_storage_is_persisted(screen: Screen):
     screen.open('/')
     screen.open('/')
     screen.open('/')
     screen.open('/')
     screen.open('/')
     screen.open('/')
-    screen.should_contain('individual: 3')
+    screen.should_contain('user: 3')
     screen.should_contain('general: 3')
     screen.should_contain('general: 3')
     screen.click('backup')
     screen.click('backup')
     screen.selenium.delete_all_cookies()
     screen.selenium.delete_all_cookies()
     screen.open('/')
     screen.open('/')
-    screen.should_contain('individual: 1')
+    screen.should_contain('user: 1')
     screen.should_contain('general: 4')
     screen.should_contain('general: 4')