1
0

pin.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. """
  2. ``pywebio.pin`` --- Persistent input
  3. ===========================================================================
  4. *pin == Persistent input == Pinning input widget to the page*
  5. Overview
  6. ------------------
  7. As you already know, the input function of PyWebIO is blocking
  8. and the input form will be destroyed after successful submission.
  9. In most cases, it enough to use this way to get input.
  10. However in some cases, you may want to make the input form **not** disappear after submission,
  11. and can continue to receive input.
  12. So PyWebIO provides the ``pin`` module to achieve persistent input by pinning input widgets to the page.
  13. The ``pin`` module achieves persistent input in 3 parts:
  14. First, this module provides some pin widgets.
  15. Pin widgets are not different from output widgets in ``pywebio.output`` module,
  16. besides that they can also receive input.
  17. This code outputs an text input pin widget:
  18. .. exportable-codeblock::
  19. :name: pin-put_input
  20. :summary: `put_input()` example
  21. put_input('input', label='This is a input widget')
  22. In fact, the usage of pin widget function is same as the output function.
  23. You can use it as part of the combined output, or you can output pin widget to a scope:
  24. .. exportable-codeblock::
  25. :name: pin-basic
  26. :summary: Pin widget as output function
  27. put_row([
  28. put_input('input'),
  29. put_select('select', options=['A', 'B', 'C'])
  30. ])
  31. with use_scope('search-area'):
  32. put_input('search', placeholder='Search')
  33. Then, you can use the `pin` object to get the value of pin widget:
  34. .. exportable-codeblock::
  35. :name: get-pin-value
  36. :summary: Use the `pin` object to get the value of pin widget
  37. put_input('pin_name')
  38. put_buttons(['Get Pin Value'], lambda _: put_text(pin.pin_name))
  39. The first parameter that the pin widget function receives is the name of the pin widget.
  40. You can get the current value of the pin widget via the attribute of the same name of the `pin` object.
  41. In addition, the `pin` object also supports getting the value of the pin widget by index, that is to say::
  42. pin['pin_name'] == pin.pin_name
  43. There are also two useful functions when you use the pin module: `pin_wait_change()` and `pin_update()`.
  44. Since the pin widget functions is not blocking,
  45. `pin_wait_change()` is used to wait for the value of one of a list of pin widget to change, it 's a blocking function.
  46. `pin_update()` can be used to update attributes of pin widgets.
  47. Pin widgets
  48. ------------------
  49. Each pin widget function corresponds to an input function of :doc:`input <./input>` module.
  50. (For performance reasons, no pin widget for `file_upload() <pywebio.input.file_upload>` input function)
  51. The function of pin widget supports most of the parameters of the corresponding input function.
  52. Here lists the difference between the two in parameters:
  53. * The first parameter of pin widget function is always the name of the widget,
  54. and if you output two pin widgets with the same name, the previous one will expire.
  55. * Pin functions don't support the ``on_change`` and ``validate`` callbacks, and the ``required`` parameter.
  56. * Pin functions have additional ``scope`` and ``position`` parameters for output control.
  57. .. autofunction:: put_input
  58. .. autofunction:: put_textarea
  59. .. autofunction:: put_select
  60. .. autofunction:: put_checkbox
  61. .. autofunction:: put_radio
  62. .. autofunction:: put_slider
  63. .. autofunction:: put_actions
  64. Pin utils
  65. ------------------
  66. .. data:: pin
  67. Pin widgets value getter and setter.
  68. You can use attribute or key index of ``pin`` object to get the current value of a pin widget.
  69. When accessing the value of a widget that does not exist, it returns ``None`` instead of throwing an exception.
  70. You can also use the ``pin`` object to set the value of pin widget:
  71. .. exportable-codeblock::
  72. :name: set-pin-value
  73. :summary: Use the `pin` object to set the value of pin widget
  74. import time # ..demo-only
  75. put_input('counter', type='number', value=0)
  76. while True:
  77. pin.counter = pin.counter + 1 # Equivalent to: pin['counter'] = pin['counter'] + 1
  78. time.sleep(1)
  79. Note: When using :ref:`coroutine-based session <coroutine_based_session>`,
  80. you need to use the ``await pin.name`` (or ``await pin['name']``) syntax to get pin widget value.
  81. .. autofunction:: pin_wait_change
  82. .. autofunction:: pin_update
  83. """
  84. import string
  85. from pywebio.input import parse_input_update_spec
  86. from pywebio.output import OutputPosition, Output
  87. from pywebio.output import _get_output_spec
  88. from .io_ctrl import send_msg, single_input_kwargs
  89. from .session import next_client_event, chose_impl
  90. _html_value_chars = set(string.ascii_letters + string.digits + '_')
  91. __all__ = ['put_input', 'put_textarea', 'put_select', 'put_checkbox', 'put_radio', 'put_slider', 'put_actions',
  92. 'pin', 'pin_update', 'pin_wait_change']
  93. def check_name(name):
  94. assert all(i in _html_value_chars for i in name), "pin `name` can only contain letters, digits and underscore"
  95. assert name[0] in string.ascii_letters, "pin `name` can only starts with letters"
  96. def _pin_output(single_input_return, scope, position):
  97. input_kwargs = single_input_kwargs(single_input_return)
  98. spec = _get_output_spec('pin', input=input_kwargs['item_spec'], scope=scope, position=position)
  99. return Output(spec)
  100. def put_input(name, type='text', *, label='', value=None, placeholder=None, readonly=None, datalist=None,
  101. help_text=None, scope=None, position=OutputPosition.BOTTOM) -> Output:
  102. """Output an input widget. Refer to: `pywebio.input.input()`"""
  103. from pywebio.input import input
  104. check_name(name)
  105. single_input_return = input(name=name, label=label, value=value, type=type, placeholder=placeholder,
  106. readonly=readonly, datalist=datalist, help_text=help_text)
  107. return _pin_output(single_input_return, scope, position)
  108. def put_textarea(name, *, label='', rows=6, code=None, maxlength=None, minlength=None, value=None, placeholder=None,
  109. readonly=None, help_text=None, scope=None, position=OutputPosition.BOTTOM) -> Output:
  110. """Output a textarea widget. Refer to: `pywebio.input.textarea()`"""
  111. from pywebio.input import textarea
  112. check_name(name)
  113. single_input_return = textarea(
  114. name=name, label=label, rows=rows, code=code, maxlength=maxlength,
  115. minlength=minlength, value=value, placeholder=placeholder, readonly=readonly, help_text=help_text)
  116. return _pin_output(single_input_return, scope, position)
  117. def put_select(name, options=None, *, label='', multiple=None, value=None, help_text=None,
  118. scope=None, position=OutputPosition.BOTTOM) -> Output:
  119. """Output a select widget. Refer to: `pywebio.input.select()`"""
  120. from pywebio.input import select
  121. check_name(name)
  122. single_input_return = select(name=name, options=options, label=label, multiple=multiple,
  123. value=value, help_text=help_text)
  124. return _pin_output(single_input_return, scope, position)
  125. def put_checkbox(name, options=None, *, label='', inline=None, value=None, help_text=None,
  126. scope=None, position=OutputPosition.BOTTOM) -> Output:
  127. """Output a checkbox widget. Refer to: `pywebio.input.checkbox()`"""
  128. from pywebio.input import checkbox
  129. check_name(name)
  130. single_input_return = checkbox(name=name, options=options, label=label, inline=inline, value=value,
  131. help_text=help_text)
  132. return _pin_output(single_input_return, scope, position)
  133. def put_radio(name, options=None, *, label='', inline=None, value=None, help_text=None,
  134. scope=None, position=OutputPosition.BOTTOM) -> Output:
  135. """Output a radio widget. Refer to: `pywebio.input.radio()`"""
  136. from pywebio.input import radio
  137. check_name(name)
  138. single_input_return = radio(name=name, options=options, label=label, inline=inline, value=value,
  139. help_text=help_text)
  140. return _pin_output(single_input_return, scope, position)
  141. def put_slider(name, *, label='', value=0, min_value=0, max_value=100, step=1, required=None, help_text=None,
  142. scope=None, position=OutputPosition.BOTTOM) -> Output:
  143. """Output a slide widget. Refer to: `pywebio.input.slider()`"""
  144. from pywebio.input import slider
  145. check_name(name)
  146. single_input_return = slider(name=name, label=label, value=value, min_value=min_value, max_value=max_value,
  147. step=step, required=required, help_text=help_text)
  148. return _pin_output(single_input_return, scope, position)
  149. def put_actions(name, *, label='', buttons=None, help_text=None,
  150. scope=None, position=OutputPosition.BOTTOM) -> Output:
  151. """Output a group of action button. Refer to: `pywebio.input.actions()`
  152. Unlike the ``actions()``, ``put_actions()`` won't submit any form, it will only set the value of the pin widget.
  153. Only 'submit' type button is available in pin widget version.
  154. .. versionadded:: 1.4
  155. """
  156. from pywebio.input import actions
  157. check_name(name)
  158. single_input_return = actions(name=name, label=label, buttons=buttons, help_text=help_text)
  159. input_kwargs = single_input_kwargs(single_input_return)
  160. for btn in input_kwargs['item_spec']['buttons']:
  161. assert btn['type'] == 'submit', "The `put_actions()` pin widget only accept 'submit' type button."
  162. return _pin_output(input_kwargs, scope, position)
  163. @chose_impl
  164. def get_client_val():
  165. res = yield next_client_event()
  166. assert res['event'] == 'js_yield', "Internal Error, please report this bug on " \
  167. "https://github.com/wang0618/PyWebIO/issues"
  168. return res['data']
  169. class Pin_:
  170. def __getattr__(self, name):
  171. """__getattr__ is only invoked if the attribute wasn't found the usual ways"""
  172. check_name(name)
  173. send_msg('pin_value', spec=dict(name=name))
  174. return get_client_val()
  175. def __getitem__(self, name):
  176. return self.__getattr__(name)
  177. def __setattr__(self, name, value):
  178. """
  179. __setattr__ will be invoked regardless of whether the attribute be found
  180. """
  181. check_name(name)
  182. send_msg('pin_update', spec=dict(name=name, attributes={"value": value}))
  183. def __setitem__(self, name, value):
  184. self.__setitem__(name, value)
  185. # pin widgets value getter (and setter).
  186. pin = Pin_()
  187. def pin_wait_change(*names, timeout=None):
  188. """``pin_wait_change()`` listens to a list of pin widgets, when the value of any widgets changes,
  189. the function returns with the name and value of the changed widget.
  190. :param str names: List of names of pin widget
  191. :param int/None timeout: If ``timeout`` is a positive number, ``pin_wait_change()`` blocks at most ``timeout`` seconds
  192. and returns ``None`` if no changes to the widgets within that time. Set to ``None`` (the default) to disable timeout.
  193. :return dict/None: ``{"name": name of the changed widget, "value": current value of the changed widget }`` ,
  194. when a timeout occurs, return ``None``.
  195. Example:
  196. .. exportable-codeblock::
  197. :name: pin_wait_change
  198. :summary: `pin_wait_change()` example
  199. put_input('a', type='number', value=0)
  200. put_input('b', type='number', value=0)
  201. while True:
  202. changed = pin_wait_change('a', 'b')
  203. with use_scope('res', clear=True):
  204. put_code(changed)
  205. put_text("a + b = %s" % (pin.a + pin.b))
  206. :demo_host:`Here </markdown_previewer>` is an demo of using `pin_wait_change()` to make a markdown previewer.
  207. Note that: updating value with the :data:`pin` object or `pin_update()`
  208. does not trigger `pin_wait_change()` to return.
  209. When using :ref:`coroutine-based session <coroutine_based_session>`,
  210. you need to use the ``await pin_wait_change()`` syntax to invoke this function.
  211. """
  212. assert len(names) >= 1, "`names` can't be empty."
  213. if len(names) == 1 and isinstance(names[0], (list, tuple)):
  214. names = names[0]
  215. send_msg('pin_wait', spec=dict(names=names, timeout=timeout))
  216. return get_client_val()
  217. def pin_update(name, **spec):
  218. """Update attributes of pin widgets.
  219. :param str name: The ``name`` of the target input widget.
  220. :param spec: The pin widget parameters need to be updated.
  221. Note that those parameters can not be updated: ``type``, ``name``, ``code``, ``multiple``
  222. """
  223. check_name(name)
  224. attributes = parse_input_update_spec(spec)
  225. send_msg('pin_update', spec=dict(name=name, attributes=attributes))