storage_documentation.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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`:
  10. Stored server-side, each dictionary is associated with a unique identifier held in a browser session cookie.
  11. Unique to each user, this storage is accessible across all their browser tabs.
  12. - `app.storage.general`:
  13. Also stored server-side, this dictionary provides a shared storage space accessible to all users.
  14. - `app.storage.browser`:
  15. Unlike the previous types, this dictionary is stored directly as the browser session cookie, shared among all browser tabs for the same user.
  16. However, `app.storage.user` is generally preferred due to its advantages in reducing data payload, enhancing security, and offering larger storage capacity.
  17. To use the user or browser storage, you must pass a `storage_secret` to `ui.run()`.
  18. This is a private key used to encrypt the browser session cookie.
  19. """
  20. from nicegui import app
  21. # @ui.page('/')
  22. # def index():
  23. # app.storage.user['count'] = app.storage.user.get('count', 0) + 1
  24. # with ui.row():
  25. # ui.label('your own page visits:')
  26. # ui.label().bind_text_from(app.storage.user, 'count')
  27. #
  28. # ui.run(storage_secret='private key to secure the browser session cookie')
  29. # END OF DEMO
  30. app.storage.user['count'] = app.storage.user.get('count', 0) + 1
  31. with ui.row():
  32. ui.label('your own page visits:')
  33. ui.label().bind_text_from(app.storage.user, 'count')
  34. counter = Counter()
  35. start = datetime.now().strftime('%H:%M, %d %B %Y')
  36. def more() -> None:
  37. @text_demo('Counting page visits', '''
  38. Here we are using the automatically available browser-stored session ID to count the number of unique page visits.
  39. ''')
  40. def page_visits():
  41. from collections import Counter
  42. from datetime import datetime
  43. from nicegui import app
  44. # counter = Counter()
  45. # start = datetime.now().strftime('%H:%M, %d %B %Y')
  46. #
  47. # @ui.page('/')
  48. # def index():
  49. # counter[app.storage.session.browser[id]] += 1
  50. # ui.label(f'{len(counter)} unique views ({sum(counter.values())} overall) since {start}')
  51. #
  52. # ui.run(storage_secret='private key to secure the browser session cookie')
  53. # END OF DEMO
  54. counter[app.storage.browser['id']] += 1
  55. ui.label(f'{len(counter)} unique views ({sum(counter.values())} overall) since {start}')