section_action_events.py 4.7 KB

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