storage_documentation.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from collections import Counter
  2. from datetime import datetime
  3. from nicegui import ui
  4. from ..documentation_tools import text_demo
  5. def main_demo() -> None:
  6. """Storage
  7. NiceGUI offers a straightforward method for data persistence within your application.
  8. It features three built-in storage types:
  9. - `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.
  10. - app.storage.general`: Also stored server-side, this dictionary provides a shared storage space accessible to all users.
  11. - `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.
  12. To use the user or browser storage, you must pass a `storage_secret` to `ui.run()`.
  13. This is a private key used to encrypt the browser session cookie.
  14. """
  15. from nicegui import app
  16. # @ui.page('/')
  17. # def index():
  18. # app.storage.user['count'] = app.storage.user.get('count', 0) + 1
  19. # with ui.row():
  20. # ui.label('your own page visits:')
  21. # ui.label().bind_text_from(app.storage.user, 'count')
  22. #
  23. # ui.run(storage_secret='private key to secure the browser session cookie')
  24. # END OF DEMO
  25. app.storage.user['count'] = app.storage.user.get('count', 0) + 1
  26. with ui.row():
  27. ui.label('your own page visits:')
  28. ui.label().bind_text_from(app.storage.user, 'count')
  29. counter = Counter()
  30. start = datetime.now().strftime('%H:%M, %d %B %Y')
  31. def more() -> None:
  32. @text_demo('Counting page visits', '''
  33. Here we are using the automatically available browser stored session id to count the number of unique page visits.
  34. ''')
  35. def page_visits():
  36. from collections import Counter
  37. from datetime import datetime
  38. from nicegui import app
  39. # counter = Counter()
  40. # start = datetime.now().strftime('%H:%M, %d %B %Y')
  41. #
  42. # @ui.page('/')
  43. # def index():
  44. # counter[app.storage.session.browser[id]] += 1
  45. # ui.label(f'{len(counter)} unique views ({sum(counter.values())} overall) since {start}')
  46. #
  47. # ui.run(storage_secret='private key to secure the browser session cookie')
  48. # END OF DEMO
  49. counter[app.storage.browser['id']] += 1
  50. ui.label(f'{len(counter)} unique views ({sum(counter.values())} overall) since {start}')