storage_documentation.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. from collections import Counter
  2. from datetime import datetime
  3. from nicegui import ui
  4. from . import doc
  5. counter = Counter() # type: ignore
  6. start = datetime.now().strftime(r'%H:%M, %d %B %Y')
  7. doc.title('Storage')
  8. @doc.demo('Storage', '''
  9. NiceGUI offers a straightforward mechanism for data persistence within your application.
  10. It features four built-in storage types:
  11. - `app.storage.tab`:
  12. Stored server-side in memory, this dictionary is unique to each tab session and can hold arbitrary objects.
  13. Data will be lost when restarting the server until <https://github.com/zauberzeug/nicegui/discussions/2841> is implemented.
  14. This storage is only available within [page builder functions](/documentation/page)
  15. and requires an established connection, obtainable via [`await client.connected()`](/documentation/page#wait_for_client_connection).
  16. - `app.storage.user`:
  17. Stored server-side, each dictionary is associated with a unique identifier held in a browser session cookie.
  18. Unique to each user, this storage is accessible across all their browser tabs.
  19. `app.storage.browser['id']` is used to identify the user.
  20. - `app.storage.general`:
  21. Also stored server-side, this dictionary provides a shared storage space accessible to all users.
  22. - `app.storage.browser`:
  23. Unlike the previous types, this dictionary is stored directly as the browser session cookie, shared among all browser tabs for the same user.
  24. However, `app.storage.user` is generally preferred due to its advantages in reducing data payload, enhancing security, and offering larger storage capacity.
  25. By default, NiceGUI holds a unique identifier for the browser session in `app.storage.browser['id']`.
  26. The user storage and browser storage are only available within `page builder functions </documentation/page>`_
  27. because they are accessing the underlying `Request` object from FastAPI.
  28. Additionally these two types require the `storage_secret` parameter in`ui.run()` to encrypt the browser session cookie.
  29. ''')
  30. def storage_demo():
  31. from nicegui import app
  32. # @ui.page('/')
  33. # def index():
  34. # app.storage.user['count'] = app.storage.user.get('count', 0) + 1
  35. # with ui.row():
  36. # ui.label('your own page visits:')
  37. # ui.label().bind_text_from(app.storage.user, 'count')
  38. #
  39. # ui.run(storage_secret='private key to secure the browser session cookie')
  40. # END OF DEMO
  41. app.storage.user['count'] = app.storage.user.get('count', 0) + 1
  42. with ui.row():
  43. ui.label('your own page visits:')
  44. ui.label().bind_text_from(app.storage.user, 'count')
  45. @doc.demo('Counting page visits', '''
  46. Here we are using the automatically available browser-stored session ID to count the number of unique page visits.
  47. ''')
  48. def page_visits():
  49. from collections import Counter
  50. from datetime import datetime
  51. from nicegui import app
  52. # counter = Counter()
  53. # start = datetime.now().strftime('%H:%M, %d %B %Y')
  54. #
  55. # @ui.page('/')
  56. # def index():
  57. # counter[app.storage.browser['id']] += 1
  58. # ui.label(f'{len(counter)} unique views ({sum(counter.values())} overall) since {start}')
  59. #
  60. # ui.run(storage_secret='private key to secure the browser session cookie')
  61. # END OF DEMO
  62. counter[app.storage.browser['id']] += 1
  63. ui.label(f'{len(counter)} unique views ({sum(counter.values())} overall) since {start}')
  64. @doc.demo('Storing UI state', '''
  65. Storage can also be used in combination with [`bindings`](/documentation/bindings).
  66. Here we are storing the value of a textarea between visits.
  67. The note is also shared between all tabs of the same user.
  68. ''')
  69. def ui_state():
  70. from nicegui import app
  71. # @ui.page('/')
  72. # def index():
  73. # ui.textarea('This note is kept between visits') \
  74. # .classes('w-full').bind_value(app.storage.user, 'note')
  75. # END OF DEMO
  76. ui.textarea('This note is kept between visits').classes('w-full').bind_value(app.storage.user, 'note')
  77. @doc.demo('Storing data per browser tab', '''
  78. When storing data in `app.storage.tab`, a single user can open multiple tabs of the same app, each with its own storage data.
  79. This may be beneficial in certain scenarios like search or when performing data analysis.
  80. It is also more secure to use such a volatile storage for scenarios like logging into a bank account or accessing a password manager.
  81. ''')
  82. def tab_storage():
  83. from nicegui import app
  84. # @ui.page('/')
  85. # async def index(client):
  86. # await client.connected()
  87. with ui.column(): # HIDE
  88. app.storage.tab['count'] = app.storage.tab.get('count', 0) + 1
  89. ui.label(f'Tab reloaded {app.storage.tab["count"]} times')