pin.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. (There is a :func:`pin_on_change()` function as an alternative to ``on_change``)
  57. * Pin functions have additional ``scope`` and ``position`` parameters for output control.
  58. .. autofunction:: put_input
  59. .. autofunction:: put_textarea
  60. .. autofunction:: put_select
  61. .. autofunction:: put_checkbox
  62. .. autofunction:: put_radio
  63. .. autofunction:: put_slider
  64. .. autofunction:: put_actions
  65. Pin utils
  66. ------------------
  67. .. data:: pin
  68. Pin widgets value getter and setter.
  69. You can use attribute or key index of ``pin`` object to get the current value of a pin widget.
  70. By default, when accessing the value of a widget that does not exist, it returns ``None`` instead of
  71. throwing an exception.
  72. You can also use the ``pin`` object to set the value of pin widget:
  73. .. exportable-codeblock::
  74. :name: set-pin-value
  75. :summary: Use the `pin` object to set the value of pin widget
  76. import time # ..demo-only
  77. put_input('counter', type='number', value=0)
  78. while True:
  79. pin.counter = pin.counter + 1 # Equivalent to: pin['counter'] = pin['counter'] + 1
  80. time.sleep(1)
  81. Note: When using :ref:`coroutine-based session <coroutine_based_session>`,
  82. you need to use the ``await pin.name`` (or ``await pin['name']``) syntax to get pin widget value.
  83. Use `pin.pin.use_strict()` to enable strict mode for getting pin widget value.
  84. An ``AssertionError`` will be raised when try to get value of pin widgets that are currently not in the page.
  85. .. autofunction:: pin_wait_change
  86. .. autofunction:: pin_update
  87. .. autofunction:: pin_on_change
  88. """
  89. import string
  90. from pywebio.input import parse_input_update_spec
  91. from pywebio.output import OutputPosition, Output
  92. from pywebio.output import _get_output_spec
  93. from .io_ctrl import send_msg, single_input_kwargs, output_register_callback
  94. from .session import next_client_event, chose_impl
  95. from .utils import check_dom_name_value
  96. _pin_name_chars = set(string.ascii_letters + string.digits + '_-')
  97. __all__ = ['put_input', 'put_textarea', 'put_select', 'put_checkbox', 'put_radio', 'put_slider', 'put_actions',
  98. 'pin', 'pin_update', 'pin_wait_change', 'pin_on_change']
  99. def _pin_output(single_input_return, scope, position):
  100. input_kwargs = single_input_kwargs(single_input_return)
  101. spec = _get_output_spec('pin', input=input_kwargs['item_spec'], scope=scope, position=position)
  102. return Output(spec)
  103. def put_input(name, type='text', *, label='', value=None, placeholder=None, readonly=None, datalist=None,
  104. help_text=None, scope=None, position=OutputPosition.BOTTOM) -> Output:
  105. """Output an input widget. Refer to: `pywebio.input.input()`"""
  106. from pywebio.input import input
  107. check_dom_name_value(name, 'pin `name`')
  108. single_input_return = input(name=name, label=label, value=value, type=type, placeholder=placeholder,
  109. readonly=readonly, datalist=datalist, help_text=help_text)
  110. return _pin_output(single_input_return, scope, position)
  111. def put_textarea(name, *, label='', rows=6, code=None, maxlength=None, minlength=None, value=None, placeholder=None,
  112. readonly=None, help_text=None, scope=None, position=OutputPosition.BOTTOM) -> Output:
  113. """Output a textarea widget. Refer to: `pywebio.input.textarea()`"""
  114. from pywebio.input import textarea
  115. check_dom_name_value(name, 'pin `name`')
  116. single_input_return = textarea(
  117. name=name, label=label, rows=rows, code=code, maxlength=maxlength,
  118. minlength=minlength, value=value, placeholder=placeholder, readonly=readonly, help_text=help_text)
  119. return _pin_output(single_input_return, scope, position)
  120. def put_select(name, options=None, *, label='', multiple=None, value=None, help_text=None,
  121. scope=None, position=OutputPosition.BOTTOM) -> Output:
  122. """Output a select widget. Refer to: `pywebio.input.select()`"""
  123. from pywebio.input import select
  124. check_dom_name_value(name, 'pin `name`')
  125. single_input_return = select(name=name, options=options, label=label, multiple=multiple,
  126. value=value, help_text=help_text)
  127. return _pin_output(single_input_return, scope, position)
  128. def put_checkbox(name, options=None, *, label='', inline=None, value=None, help_text=None,
  129. scope=None, position=OutputPosition.BOTTOM) -> Output:
  130. """Output a checkbox widget. Refer to: `pywebio.input.checkbox()`"""
  131. from pywebio.input import checkbox
  132. check_dom_name_value(name, 'pin `name`')
  133. single_input_return = checkbox(name=name, options=options, label=label, inline=inline, value=value,
  134. help_text=help_text)
  135. return _pin_output(single_input_return, scope, position)
  136. def put_radio(name, options=None, *, label='', inline=None, value=None, help_text=None,
  137. scope=None, position=OutputPosition.BOTTOM) -> Output:
  138. """Output a radio widget. Refer to: `pywebio.input.radio()`"""
  139. from pywebio.input import radio
  140. check_dom_name_value(name, 'pin `name`')
  141. single_input_return = radio(name=name, options=options, label=label, inline=inline, value=value,
  142. help_text=help_text)
  143. return _pin_output(single_input_return, scope, position)
  144. def put_slider(name, *, label='', value=0, min_value=0, max_value=100, step=1, required=None, help_text=None,
  145. scope=None, position=OutputPosition.BOTTOM) -> Output:
  146. """Output a slide widget. Refer to: `pywebio.input.slider()`"""
  147. from pywebio.input import slider
  148. check_dom_name_value(name, 'pin `name`')
  149. single_input_return = slider(name=name, label=label, value=value, min_value=min_value, max_value=max_value,
  150. step=step, required=required, help_text=help_text)
  151. return _pin_output(single_input_return, scope, position)
  152. def put_actions(name, *, label='', buttons=None, help_text=None,
  153. scope=None, position=OutputPosition.BOTTOM) -> Output:
  154. """Output a group of action button. Refer to: `pywebio.input.actions()`
  155. Unlike the ``actions()``, ``put_actions()`` won't submit any form, it will only set the value of the pin widget.
  156. Only 'submit' type button is available in pin widget version.
  157. .. versionadded:: 1.4
  158. """
  159. from pywebio.input import actions
  160. check_dom_name_value(name, 'pin `name`')
  161. single_input_return = actions(name=name, label=label, buttons=buttons, help_text=help_text)
  162. input_kwargs = single_input_kwargs(single_input_return)
  163. for btn in input_kwargs['item_spec']['buttons']:
  164. assert btn['type'] == 'submit', "The `put_actions()` pin widget only accept 'submit' type button."
  165. return _pin_output(input_kwargs, scope, position)
  166. @chose_impl
  167. def get_client_val():
  168. res = yield next_client_event()
  169. assert res['event'] == 'js_yield', "Internal Error, please report this bug on " \
  170. "https://github.com/wang0618/PyWebIO/issues"
  171. return res['data']
  172. @chose_impl
  173. def get_pin_value(name, strict):
  174. send_msg('pin_value', spec=dict(name=name))
  175. data = yield get_client_val()
  176. assert not strict or data, 'pin widget "%s" doesn\'t exist.' % name
  177. return (data or {}).get('value')
  178. class Pin_:
  179. _strict = False
  180. def use_strict(self):
  181. """
  182. Enable strict mode for getting pin widget value.
  183. An AssertionError will be raised when try to get value of pin widgets that are currently not in the page.
  184. """
  185. object.__setattr__(self, '_strict', True)
  186. def __getattr__(self, name):
  187. """__getattr__ is only invoked if the attribute wasn't found the usual ways"""
  188. if name.startswith('__'):
  189. raise AttributeError('Pin object has no attribute %r' % name)
  190. return self.__getitem__(name)
  191. def __getitem__(self, name):
  192. check_dom_name_value(name, 'pin `name`')
  193. return get_pin_value(name, self._strict)
  194. def __setattr__(self, name, value):
  195. """
  196. __setattr__ will be invoked regardless of whether the attribute be found
  197. """
  198. assert name != 'use_strict', "'use_strict' is a reserve name, can't use as pin widget name"
  199. check_dom_name_value(name, 'pin `name`')
  200. self.__setitem__(name, value)
  201. def __setitem__(self, name, value):
  202. send_msg('pin_update', spec=dict(name=name, attributes={"value": value}))
  203. # pin widgets value getter (and setter).
  204. pin = Pin_()
  205. def pin_wait_change(*names, timeout=None):
  206. """``pin_wait_change()`` listens to a list of pin widgets, when the value of any widgets changes,
  207. the function returns with the name and value of the changed widget.
  208. :param str names: List of names of pin widget
  209. :param int/None timeout: If ``timeout`` is a positive number, ``pin_wait_change()`` blocks at most ``timeout`` seconds
  210. and returns ``None`` if no changes to the widgets within that time. Set to ``None`` (the default) to disable timeout.
  211. :return dict/None: ``{"name": name of the changed widget, "value": current value of the changed widget }`` ,
  212. when a timeout occurs, return ``None``.
  213. Example:
  214. .. exportable-codeblock::
  215. :name: pin_wait_change
  216. :summary: `pin_wait_change()` example
  217. put_input('a', type='number', value=0)
  218. put_input('b', type='number', value=0)
  219. while True:
  220. changed = pin_wait_change('a', 'b')
  221. with use_scope('res', clear=True):
  222. put_code(changed)
  223. put_text("a + b = %s" % (pin.a + pin.b))
  224. :demo_host:`Here </markdown_previewer>` is an demo of using `pin_wait_change()` to make a markdown previewer.
  225. Note that: updating value with the :data:`pin` object or `pin_update()`
  226. does not trigger `pin_wait_change()` to return.
  227. When using :ref:`coroutine-based session <coroutine_based_session>`,
  228. you need to use the ``await pin_wait_change()`` syntax to invoke this function.
  229. """
  230. assert len(names) >= 1, "`names` can't be empty."
  231. if len(names) == 1 and isinstance(names[0], (list, tuple)):
  232. names = names[0]
  233. send_msg('pin_wait', spec=dict(names=names, timeout=timeout))
  234. return get_client_val()
  235. def pin_update(name, **spec):
  236. """Update attributes of pin widgets.
  237. :param str name: The ``name`` of the target input widget.
  238. :param spec: The pin widget parameters need to be updated.
  239. Note that those parameters can not be updated: ``type``, ``name``, ``code``, ``multiple``
  240. """
  241. check_dom_name_value(name, 'pin `name`')
  242. attributes = parse_input_update_spec(spec)
  243. send_msg('pin_update', spec=dict(name=name, attributes=attributes))
  244. def pin_on_change(name, onchange=None, clear=False, init_run=False, **callback_options):
  245. """
  246. Bind a callback function to pin widget, the function will be called when user change the value of the pin widget.
  247. The ``onchange`` callback is invoked with one argument, the changed value of the pin widget.
  248. You can bind multiple functions to one pin widget, those functions will be invoked sequentially
  249. (default behavior, can be changed by `clear` parameter).
  250. :param str name: pin widget name
  251. :param callable onchange: callback function
  252. :param bool clear: whether to clear the previous callbacks bound to this pin widget.
  253. If you just want to clear callbacks and not set new callback, use ``pin_on_change(name, clear=True)``.
  254. :param bool init_run: whether to run the ``onchange`` callback once immediately before the pin widget changed.
  255. This parameter can be used to initialize the output.
  256. :param callback_options: Other options of the ``onclick`` callback.
  257. Refer to the ``callback_options`` parameter of :func:`put_buttons() <pywebio.output.put_buttons>`
  258. .. versionadded:: 1.6
  259. """
  260. assert not (onchange is None and clear is False), "When `onchange` is `None`, `clear` must be `True`"
  261. if onchange is not None:
  262. callback_id = output_register_callback(onchange, **callback_options)
  263. if init_run:
  264. onchange(pin[name])
  265. else:
  266. callback_id = None
  267. send_msg('pin_onchange', spec=dict(name=name, callback_id=callback_id, clear=clear))