action_events.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. from nicegui import app, ui
  2. from ..tools import element_demo, load_demo, subheading, text_demo
  3. name = 'action_events'
  4. title = 'Action Events'
  5. def intro() -> None:
  6. ...
  7. def content() -> None:
  8. load_demo(ui.timer)
  9. load_demo(ui.keyboard)
  10. @text_demo('UI Updates', '''
  11. NiceGUI tries to automatically synchronize the state of UI elements with the client,
  12. e.g. when a label text, an input value or style/classes/props of an element have changed.
  13. In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
  14. The demo code shows both methods for a `ui.echart`, where it is difficult to automatically detect changes in the `options` dictionary.
  15. ''')
  16. def ui_updates_demo():
  17. from random import random
  18. chart = ui.echart({
  19. 'xAxis': {'type': 'value'},
  20. 'yAxis': {'type': 'value'},
  21. 'series': [{'type': 'line', 'data': [[0, 0], [1, 1]]}],
  22. })
  23. def add():
  24. chart.options['series'][0]['data'].append([random(), random()])
  25. chart.update()
  26. def clear():
  27. chart.options['series'][0]['data'].clear()
  28. ui.update(chart)
  29. with ui.row():
  30. ui.button('Add', on_click=add)
  31. ui.button('Clear', on_click=clear)
  32. load_demo(ui.refreshable)
  33. @text_demo('Async event handlers', '''
  34. Most elements also support asynchronous event handlers.
  35. Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
  36. ''')
  37. def async_handlers_demo():
  38. import asyncio
  39. async def async_task():
  40. ui.notify('Asynchronous task started')
  41. await asyncio.sleep(5)
  42. ui.notify('Asynchronous task finished')
  43. ui.button('start async task', on_click=async_task)
  44. load_demo('generic_events')
  45. @text_demo('Running CPU-bound tasks', '''
  46. NiceGUI provides a `cpu_bound` function for running CPU-bound tasks in a separate process.
  47. This is useful for long-running computations that would otherwise block the event loop and make the UI unresponsive.
  48. The function returns a future that can be awaited.
  49. ''')
  50. def cpu_bound_demo():
  51. import time
  52. from nicegui import run
  53. def compute_sum(a: float, b: float) -> float:
  54. time.sleep(1) # simulate a long-running computation
  55. return a + b
  56. async def handle_click():
  57. result = await run.cpu_bound(compute_sum, 1, 2)
  58. ui.notify(f'Sum is {result}')
  59. # ui.button('Compute', on_click=handle_click)
  60. # END OF DEMO
  61. async def mock_click():
  62. import asyncio
  63. await asyncio.sleep(1)
  64. ui.notify('Sum is 3')
  65. ui.button('Compute', on_click=mock_click)
  66. @text_demo('Running I/O-bound tasks', '''
  67. NiceGUI provides an `io_bound` function for running I/O-bound tasks in a separate thread.
  68. This is useful for long-running I/O operations that would otherwise block the event loop and make the UI unresponsive.
  69. The function returns a future that can be awaited.
  70. ''')
  71. def io_bound_demo():
  72. import requests
  73. from nicegui import run
  74. async def handle_click():
  75. URL = 'https://httpbin.org/delay/1'
  76. response = await run.io_bound(requests.get, URL, timeout=3)
  77. ui.notify(f'Downloaded {len(response.content)} bytes')
  78. ui.button('Download', on_click=handle_click)
  79. load_demo(ui.run_javascript)
  80. @text_demo('Events', '''
  81. You can register coroutines or functions to be called for the following events:
  82. - `app.on_startup`: called when NiceGUI is started or restarted
  83. - `app.on_shutdown`: called when NiceGUI is shut down or restarted
  84. - `app.on_connect`: called for each client which connects (optional argument: nicegui.Client)
  85. - `app.on_disconnect`: called for each client which disconnects (optional argument: nicegui.Client)
  86. - `app.on_exception`: called when an exception occurs (optional argument: exception)
  87. When NiceGUI is shut down or restarted, all tasks still in execution will be automatically canceled.
  88. ''')
  89. def lifecycle_demo():
  90. from datetime import datetime
  91. from nicegui import app
  92. # dt = datetime.now()
  93. def handle_connection():
  94. global dt
  95. dt = datetime.now()
  96. app.on_connect(handle_connection)
  97. label = ui.label()
  98. ui.timer(1, lambda: label.set_text(f'Last new connection: {dt:%H:%M:%S}'))
  99. # END OF DEMO
  100. global dt
  101. dt = datetime.now()
  102. subheading('Shutdown')
  103. @element_demo(app.shutdown)
  104. def shutdown_demo():
  105. from nicegui import app
  106. # ui.button('shutdown', on_click=app.shutdown)
  107. #
  108. # ui.run(reload=False)
  109. # END OF DEMO
  110. ui.button('shutdown', on_click=lambda: ui.notify(
  111. 'Nah. We do not actually shutdown the documentation server. Try it in your own app!'))
  112. load_demo('storage')