storage_documentation.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import logging
  2. from nicegui import ui
  3. from ..documentation_tools import text_demo
  4. def main_demo() -> None:
  5. """Storage
  6. NiceGUI offers a straightforward method for data persistence within your application.
  7. It features three built-in storage types:
  8. - `app.storage.user`: Stored server-side, each dictionary is associated with a unique identifier held in a browser session cookie. Unique to each user, this storage is accessible across all their browser tabs.
  9. - app.storage.general`: Also stored server-side, this dictionary provides a shared storage space accessible to all users.
  10. - `app.storage.browser`: Unlike the previous types, this dictionary is stored directly as the browser session cookie, shared among all browser tabs for the same user. However, `app.storage.user` is generally preferred due to its advantages in reducing data payload, enhancing security, and offering larger storage capacity.
  11. """
  12. from nicegui import app
  13. # @ui.page('/')
  14. # def index():
  15. # app.storage.user['count'] = app.storage.user.get('count', 0) + 1
  16. # with ui.row():
  17. # ui.label('your own page visits:')
  18. # ui.label().bind_text_from(app.storage.user, 'count')
  19. #
  20. # ui.run(storage_secret='private key to secure the browser session cookie')
  21. # END OF DEMO
  22. app.storage.user['count'] = app.storage.user.get('count', 0) + 1
  23. with ui.row():
  24. ui.label('your own page visits:')
  25. ui.label().bind_text_from(app.storage.user, 'count')
  26. def more() -> None:
  27. @text_demo('Counting page visits', '''
  28. Here we are using the automatically available browser stored session id to count the number of unique page visits.
  29. ''')
  30. def page_visits():
  31. from collections import Counter
  32. from datetime import datetime
  33. from nicegui import app
  34. counter = Counter()
  35. start = datetime.now().strftime('%H:%M, %d %B %Y')
  36. @ui.page('/')
  37. def index():
  38. counter[app.storage.session.browser[id]] += 1
  39. ui.label(f'{len(counter)} unique views ({sum(counter.values())} overall) since {start}')
  40. # ui.run(storage_secret='private key to secure the browser session cookie')