storage_documentation.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import logging
  2. from nicegui import ui
  3. from ..documentation_tools import text_demo
  4. def main_demo() -> None:
  5. """Storage
  6. With `app.storage` you can easily persist data.
  7. By default there are three types of storage.
  8. `app.storage.user` is a dictionary stored on the server and identified by a generated id in a browser session cookie.
  9. That means each user gets their own storage which is shared between all browser tabs.
  10. `app.storage.general` is a dictionary stored on the server and shared between all users.
  11. Lastly `app.storage.browser` is a dictionary directly stored as the browser session cookie and shared between all browser tabs.
  12. It is normally better to use `app.storage.user` instead to reduce payload, gain improved security and have larger storage capacity).
  13. """
  14. from nicegui import app
  15. # @ui.page('/')
  16. # def index():
  17. # app.storage.user['count'] = app.storage.user.get('count', 0) + 1
  18. # with ui.row():
  19. # ui.label('your own page visits:')
  20. # ui.label().bind_text_from(app.storage.user, 'count')
  21. #
  22. # ui.run(storage_secret='private key to secure the browser session cookie')
  23. # END OF DEMO
  24. app.storage.user['count'] = app.storage.user.get('count', 0) + 1
  25. with ui.row():
  26. ui.label('your own page visits:')
  27. ui.label().bind_text_from(app.storage.user, 'count')
  28. def more() -> None:
  29. @text_demo('Counting page visits', '''
  30. Here we are using the automatically available browser stored session id to count the number of unique page visits.
  31. ''')
  32. def page_visits():
  33. from collections import Counter
  34. from datetime import datetime
  35. from nicegui import app
  36. counter = Counter()
  37. start = datetime.now().strftime('%H:%M, %d %B %Y')
  38. @ui.page('/')
  39. def index():
  40. counter[app.storage.session.browser[id]] += 1
  41. ui.label(f'{len(counter)} unique views ({sum(counter.values())} overall) since {start}')
  42. # ui.run(storage_secret='private key to secure the browser session cookie')