input.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. """
  2. This module provides functions to get all kinds of input of user from the browser
  3. There are two ways to use the input functions, one is to call the input function alone to get a single input::
  4. name = input("What's your name")
  5. print("Your name is %s" % name)
  6. The other is to use `input_group` to get multiple inputs at once::
  7. info = input_group("User info",[
  8. input('Input your name', name='name'),
  9. input('Input your age', name='age', type=NUMBER)
  10. ])
  11. print(info['name'], info['age'])
  12. When use `input_group`, you needs to provide the ``name`` parameter in each input function to identify the input items in the result.
  13. .. note::
  14. PyWebIO determines whether the input function is in `input_group` or is called alone according to whether the
  15. ``name`` parameter is passed. So when calling an input function alone, **do not** set the ``name`` parameter;
  16. when calling the input function in `input_group`, you **must** provide the ``name`` parameter.
  17. By default, the user can submit empty input value. If the user must provide a non-empty input value, you need to
  18. pass ``required=True`` to the input function (some input functions do not support the ``required`` parameter)
  19. The input functions in this module is blocking, and the input form will be destroyed after successful submission.
  20. If you want the form to always be displayed on the page and receive input continuously,
  21. you can consider the :doc:`pin <./pin>` module.
  22. Functions list
  23. -----------------
  24. .. list-table::
  25. * - Function name
  26. - Description
  27. * - `input <pywebio.input.input>`
  28. - Text input
  29. * - `textarea <pywebio.input.textarea>`
  30. - Multi-line text input
  31. * - `select <pywebio.input.select>`
  32. - Drop-down selection
  33. * - `checkbox <pywebio.input.checkbox>`
  34. - Checkbox
  35. * - `radio <pywebio.input.radio>`
  36. - Radio
  37. * - `slider <pywebio.input.slider>`
  38. - Slider
  39. * - `actions <pywebio.input.actions>`
  40. - Actions selection
  41. * - `file_upload <pywebio.input.file_upload>`
  42. - File uploading
  43. * - `input_group <pywebio.input.input_group>`
  44. - Input group
  45. * - `input_update <pywebio.input.input_update>`
  46. - Update input item
  47. Functions doc
  48. --------------
  49. """
  50. import copy
  51. import logging
  52. import os.path
  53. from collections.abc import Mapping
  54. from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  55. from .io_ctrl import input_control, output_register_callback, send_msg, single_input, single_input_kwargs
  56. from .platform import page as platform_setting
  57. from .session import get_current_session, get_current_task_id
  58. from .utils import Setter, check_dom_name_value, parse_file_size
  59. logger = logging.getLogger(__name__)
  60. TEXT = 'text'
  61. NUMBER = "number"
  62. FLOAT = "float"
  63. PASSWORD = "password"
  64. URL = "url"
  65. DATE = "date"
  66. TIME = "time"
  67. COLOR = "color"
  68. DATETIME_LOCAL = "datetime-local"
  69. DATETIME = DATETIME_LOCAL
  70. CHECKBOX = 'checkbox'
  71. RADIO = 'radio'
  72. SELECT = 'select'
  73. TEXTAREA = 'textarea'
  74. __all__ = ['TEXT', 'NUMBER', 'FLOAT', 'PASSWORD', 'URL', 'DATE',
  75. 'TIME', 'COLOR', 'DATETIME_LOCAL', 'DATETIME', 'input', 'textarea',
  76. 'select', 'checkbox', 'radio', 'actions', 'file_upload',
  77. 'slider', 'input_group', 'input_update']
  78. def _parse_args(kwargs, excludes=()):
  79. """parse the raw parameters that pass to input functions
  80. - excludes: the parameters that don't appear in returned spec
  81. - remove the parameters whose value is None
  82. :return:(spec,valid_func)
  83. """
  84. kwargs = {k: v for k, v in kwargs.items() if v is not None and k not in excludes}
  85. check_dom_name_value(kwargs.get('name', ''), '`name`')
  86. kwargs.update(kwargs.get('other_html_attrs', {}))
  87. kwargs.pop('other_html_attrs', None)
  88. if kwargs.get('validate'):
  89. kwargs['onblur'] = True
  90. valid_func = kwargs.pop('validate', lambda _: None)
  91. if kwargs.get('onchange'):
  92. onchange_func = kwargs['onchange']
  93. kwargs['onchange'] = True
  94. else:
  95. onchange_func = lambda _: None
  96. return kwargs, valid_func, onchange_func
  97. def input(label: str = '', type: str = TEXT, *, validate: Callable[[Any], Optional[str]] = None, name: str = None,
  98. value: Union[str, int] = None,
  99. action: Tuple[str, Callable[[Callable], None]] = None, onchange: Callable[[Any], None] = None,
  100. placeholder: str = None, required: bool = None,
  101. readonly: bool = None, datalist: List[str] = None, help_text: str = None, **other_html_attrs):
  102. r"""Text input
  103. :param str label: Label of input field.
  104. :param str type: Input type. Currently, supported types are:`TEXT` , `NUMBER` , `FLOAT` , `PASSWORD` , `URL` , `DATE` , `TIME`, `DATETIME`, `COLOR`
  105. The value of `DATE` , `TIME`, `DATETIME` type is a string in the format of `YYYY-MM-DD` , `HH:MM:SS` , `YYYY-MM-DDTHH:MM` respectively
  106. (`%Y-%m-%d`, `%H:%M:%S`, `%Y-%m-%dT%H:%M` in python `strptime() <https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior>`_ format).
  107. :param callable validate: Input value validation function. If provided, the validation function will be called when
  108. user completes the input field or submits the form.
  109. ``validate`` receives the input value as a parameter. When the input value is valid, it returns ``None``.
  110. When the input value is invalid, it returns an error message string.
  111. For example:
  112. .. exportable-codeblock::
  113. :name: input-valid-func
  114. :summary: `input()` validation
  115. def check_age(age):
  116. if age>30:
  117. return 'Too old'
  118. elif age<10:
  119. return 'Too young'
  120. input('Input your age', type=NUMBER, validate=check_age)
  121. :param str name: A string specifying a name for the input. Used with `input_group()` to identify different input
  122. items in the results of the input group. If call the input function alone, this parameter can **not** be set!
  123. :param str value: The initial value of the input
  124. :type action: tuple(label:str, callback:callable)
  125. :param action: Put a button on the right side of the input field, and user can click the button to set the value for the input.
  126. ``label`` is the label of the button, and ``callback`` is the callback function to set the input value when clicked.
  127. The callback is invoked with one argument, the ``set_value``. ``set_value`` is a callable object, which is
  128. invoked with one or two arguments. You can use ``set_value`` to set the value for the input.
  129. ``set_value`` can be invoked with one argument: ``set_value(value:str)``. The ``value`` parameter is the value to be set for the input.
  130. ``set_value`` can be invoked with two arguments: ``set_value(value:any, label:str)``. Each arguments are described as follows:
  131. * ``value`` : The real value of the input, can be any object. it will not be passed to the user browser.
  132. * ``label`` : The text displayed to the user
  133. When calling ``set_value`` with two arguments, the input item in web page will become read-only.
  134. The usage scenario of ``set_value(value:any, label:str)`` is: You need to dynamically generate the value of the
  135. input in the callback, and hope that the result displayed to the user is different from the actual submitted data
  136. (for example, result displayed to the user can be some user-friendly texts, and the value of the input can be
  137. objects that are easier to process)
  138. Usage example:
  139. .. exportable-codeblock::
  140. :name: input-action
  141. :summary: `input()` action usage
  142. import time
  143. def set_now_ts(set_value):
  144. set_value(int(time.time()))
  145. ts = input('Timestamp', type=NUMBER, action=('Now', set_now_ts))
  146. put_text('Timestamp:', ts) # ..demo-only
  147. ## ----
  148. from datetime import date,timedelta
  149. def select_date(set_value):
  150. with popup('Select Date'):
  151. put_buttons(['Today'], onclick=[lambda: set_value(date.today(), 'Today')])
  152. put_buttons(['Yesterday'], onclick=[lambda: set_value(date.today() - timedelta(days=1), 'Yesterday')])
  153. d = input('Date', action=('Select', select_date), readonly=True)
  154. put_text(type(d), d)
  155. Note: When using :ref:`Coroutine-based session <coroutine_based_session>` implementation, the ``callback``
  156. function can be a coroutine function.
  157. :param callable onchange: A callback function which will be called when user change the value of this input field.
  158. The ``onchange`` callback is invoked with one argument, the current value of input field.
  159. A typical usage scenario of ``onchange`` is to update other input item by using `input_update()`
  160. :param str placeholder: A hint to the user of what can be entered in the input. It will appear in the input field when it has no value set.
  161. :param bool required: Whether a value is required for the input to be submittable, default is ``False``
  162. :param bool readonly: Whether the value is readonly(not editable)
  163. :param list datalist: A list of predefined values to suggest to the user for this input. Can only be used when ``type=TEXT``
  164. :param str help_text: Help text for the input. The text will be displayed below the input field with small font
  165. :param other_html_attrs: Additional html attributes added to the input element.
  166. reference: https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/input#%E5%B1%9E%E6%80%A7
  167. :return: The value that user input.
  168. """
  169. item_spec, valid_func, onchange_func = _parse_args(locals(), excludes=('action',))
  170. # check input type
  171. allowed_type = {TEXT, NUMBER, FLOAT, PASSWORD, URL, DATE, TIME, COLOR, DATETIME_LOCAL}
  172. assert type in allowed_type, 'Input type not allowed.'
  173. value_setter = None
  174. if action:
  175. label, callback = action
  176. task_id = get_current_task_id()
  177. value_setter = Setter()
  178. def _set_value(value, label=value_setter):
  179. spec = {
  180. 'target_name': item_spec.get('name', 'data'),
  181. 'attributes': {'value': value}
  182. }
  183. if label is not value_setter:
  184. value_setter.label = label
  185. spec['attributes']['value'] = label
  186. spec['attributes']['readonly'] = True
  187. value_setter.value = value
  188. msg = dict(command='update_input', task_id=task_id, spec=spec)
  189. get_current_session().send_task_command(msg)
  190. callback_id = output_register_callback(lambda _: callback(_set_value))
  191. item_spec['action'] = dict(label=label, callback_id=callback_id)
  192. def preprocess_func(d): # Convert the original data submitted by the user
  193. if value_setter is not None and value_setter.label == d:
  194. return value_setter.value
  195. return d
  196. return single_input(item_spec, valid_func, preprocess_func, onchange_func)
  197. def textarea(label: str = '', *, rows: int = 6, code: Union[bool, Dict] = None, maxlength: int = None,
  198. minlength: int = None,
  199. validate: Callable[[Any], Optional[str]] = None, name: str = None, value: str = None,
  200. onchange: Callable[[Any], None] = None,
  201. placeholder: str = None, required: bool = None, readonly: bool = None, help_text: str = None,
  202. **other_html_attrs):
  203. r"""Text input area (multi-line text input)
  204. :param int rows: The number of visible text lines for the input area. Scroll bar will be used when content exceeds.
  205. :param int maxlength: The maximum number of characters (UTF-16 code units) that the user can enter.
  206. If this value isn't specified, the user can enter an unlimited number of characters.
  207. :param int minlength: The minimum number of characters (UTF-16 code units) required that the user should enter.
  208. :param dict/bool code: Enable a code style editor by providing the `Codemirror <https://codemirror.net/>`_ options:
  209. .. exportable-codeblock::
  210. :name: textarea-code
  211. :summary: `textarea()` code editor style
  212. res = textarea('Text area', code={
  213. 'mode': "python",
  214. 'theme': 'darcula'
  215. })
  216. put_code(res, language='python') # ..demo-only
  217. You can simply use ``code={}`` or ``code=True`` to enable code style editor.
  218. You can use ``Esc`` or ``F11`` to toggle fullscreen of code style textarea.
  219. Some commonly used Codemirror options are listed :ref:`here <codemirror_options>`.
  220. :param - label, validate, name, value, onchange, placeholder, required, readonly, help_text, other_html_attrs:
  221. Those arguments have the same meaning as for `input()`
  222. :return: The string value that user input.
  223. """
  224. item_spec, valid_func, onchange_func = _parse_args(locals())
  225. item_spec['type'] = TEXTAREA
  226. return single_input(item_spec, valid_func, lambda d: d, onchange_func)
  227. def _parse_select_options(options):
  228. # Convert the `options` parameter in the `select`, `checkbox`, and `radio` functions to a unified format
  229. # Available forms of option:
  230. # {value:, label:, [selected:,] [disabled:]}
  231. # (value, label, [selected,] [disabled])
  232. # value (label same as value)
  233. opts_res = []
  234. for opt in options:
  235. opt = copy.deepcopy(opt)
  236. if isinstance(opt, Mapping):
  237. assert 'value' in opt and 'label' in opt, 'options item must have value and label key'
  238. elif isinstance(opt, (list, tuple)):
  239. assert len(opt) > 1 and len(opt) <= 4, 'options item format error'
  240. opt = dict(zip(('label', 'value', 'selected', 'disabled'), opt))
  241. else:
  242. opt = dict(value=opt, label=opt)
  243. opts_res.append(opt)
  244. return opts_res
  245. def _set_options_selected(options, value):
  246. """set `selected` attribute for `options`"""
  247. if not isinstance(value, (list, tuple)):
  248. value = [value]
  249. for opt in options:
  250. if opt['value'] in value:
  251. opt['selected'] = True
  252. return options
  253. def select(label: str = '', options: List[Union[Dict[str, Any], Tuple, List, str]] = None, *, multiple: bool = None,
  254. validate: Callable[[Any], Optional[str]] = None, name: str = None, value: Union[List, str] = None,
  255. onchange: Callable[[Any], None] = None, native: bool = True, required: bool = None, help_text: str = None,
  256. **other_html_attrs):
  257. r"""Drop-down selection
  258. By default, only one option can be selected at a time, you can set ``multiple`` parameter to enable multiple selection.
  259. :param list options: list of options. The available formats of the list items are:
  260. * dict::
  261. {
  262. "label":(str) option label,
  263. "value":(object) option value,
  264. "selected":(bool, optional) whether the option is initially selected,
  265. "disabled":(bool, optional) whether the option is initially disabled
  266. }
  267. * tuple or list: ``(label, value, [selected,] [disabled])``
  268. * single value: label and value of option use the same value
  269. Attention:
  270. 1. The ``value`` of option can be any JSON serializable object
  271. 2. If the ``multiple`` is not ``True``, the list of options can only have one ``selected`` item at most.
  272. :param bool multiple: whether multiple options can be selected
  273. :param value: The value of the initial selected item. When ``multiple=True``, ``value`` must be a list.
  274. You can also set the initial selected option by setting the ``selected`` field in the ``options`` list item.
  275. :type value: list or str
  276. :param bool required: Whether to select at least one item, only available when ``multiple=True``
  277. :param bool native: Using browser's native select component rather than
  278. `bootstrap-select <https://github.com/snapappointments/bootstrap-select>`_. This is the default behavior.
  279. :param - label, validate, name, onchange, help_text, other_html_attrs: Those arguments have the same meaning as for `input()`
  280. :return: If ``multiple=True``, return a list of the values in the ``options`` selected by the user;
  281. otherwise, return the single value selected by the user.
  282. """
  283. assert options is not None, 'Required `options` parameter in select()'
  284. item_spec, valid_func, onchange_func = _parse_args(locals(), excludes=['value'])
  285. item_spec['options'] = _parse_select_options(options)
  286. if value is not None:
  287. item_spec['options'] = _set_options_selected(item_spec['options'], value)
  288. item_spec['type'] = SELECT
  289. return single_input(item_spec, valid_func=valid_func, preprocess_func=lambda d: d, onchange_func=onchange_func)
  290. def checkbox(label: str = '', options: List[Union[Dict[str, Any], Tuple, List, str]] = None, *, inline: bool = None,
  291. validate: Callable[[Any], Optional[str]] = None,
  292. name: str = None, value: List = None, onchange: Callable[[Any], None] = None, help_text: str = None,
  293. **other_html_attrs):
  294. r"""A group of check box that allowing single values to be selected/deselected.
  295. :param list options: List of options. The format is the same as the ``options`` parameter of the `select()` function
  296. :param bool inline: Whether to display the options on one line. Default is ``False``
  297. :param list value: The value list of the initial selected items.
  298. You can also set the initial selected option by setting the ``selected`` field in the ``options`` list item.
  299. :param - label, validate, name, onchange, help_text, other_html_attrs: Those arguments have the same meaning as for `input()`
  300. :return: A list of the values in the ``options`` selected by the user
  301. """
  302. assert options is not None, 'Required `options` parameter in checkbox()'
  303. item_spec, valid_func, onchange_func = _parse_args(locals(), excludes=['value'])
  304. item_spec['options'] = _parse_select_options(options)
  305. if value is not None:
  306. item_spec['options'] = _set_options_selected(item_spec['options'], value)
  307. item_spec['type'] = CHECKBOX
  308. return single_input(item_spec, valid_func, lambda d: d, onchange_func)
  309. def radio(label: str = '', options: List[Union[Dict[str, Any], Tuple, List, str]] = None, *, inline: bool = None,
  310. validate: Callable[[Any], Optional[str]] = None,
  311. name: str = None, value: str = None, onchange: Callable[[Any], None] = None, required: bool = None,
  312. help_text: str = None, **other_html_attrs):
  313. r"""A group of radio button. Only a single button can be selected.
  314. :param list options: List of options. The format is the same as the ``options`` parameter of the `select()` function
  315. :param bool inline: Whether to display the options on one line. Default is ``False``
  316. :param str value: The value of the initial selected items.
  317. You can also set the initial selected option by setting the ``selected`` field in the ``options`` list item.
  318. :param bool required: whether to must select one option. (the user can select nothing option by default)
  319. :param - label, validate, name, onchange, help_text, other_html_attrs: Those arguments have the same meaning as for `input()`
  320. :return: The value of the option selected by the user, if the user does not select any value, return ``None``
  321. """
  322. assert options is not None, 'Required `options` parameter in radio()'
  323. item_spec, valid_func, onchange_func = _parse_args(locals())
  324. item_spec['options'] = _parse_select_options(options)
  325. if value is not None:
  326. del item_spec['value']
  327. item_spec['options'] = _set_options_selected(item_spec['options'], value)
  328. # From https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required
  329. # In the case of a same named group of radio buttons, if a single radio button in the group has the required attribute,
  330. # a radio button in that group must be checked, although it doesn't have to be the one with the attribute is applied
  331. if required is not None:
  332. del item_spec['required']
  333. item_spec['options'][-1]['required'] = required
  334. item_spec['type'] = RADIO
  335. return single_input(item_spec, valid_func, lambda d: d, onchange_func)
  336. def _parse_action_buttons(buttons):
  337. """
  338. :param label:
  339. :param actions: action list
  340. action available format:
  341. * dict: ``{label:button label, value:button value, [type: button type], [disabled:is disabled?]}``
  342. * tuple or list: ``(label, value, [type], [disabled])``
  343. * single value: label and value of button share the same value
  344. :return: dict format
  345. """
  346. act_res = []
  347. for act in buttons:
  348. act = copy.deepcopy(act)
  349. if isinstance(act, Mapping):
  350. assert 'label' in act, 'actions item must have label key'
  351. assert 'value' in act or act.get('type', 'submit') != 'submit' or act.get('disabled'), \
  352. 'actions item must have value key for submit type'
  353. elif isinstance(act, (list, tuple)):
  354. assert len(act) in (2, 3, 4), 'actions item format error'
  355. act = dict(zip(('label', 'value', 'type', 'disabled'), act))
  356. else:
  357. act = dict(value=act, label=act)
  358. act.setdefault('type', 'submit')
  359. assert act['type'] in ('submit', 'reset', 'cancel'), \
  360. "submit type must be 'submit'/'reset'/'cancel', not %r" % act['type']
  361. act_res.append(act)
  362. return act_res
  363. def actions(label: str = '', buttons: List[Union[Dict[str, Any], Tuple, List, str]] = None, name: str = None,
  364. help_text: str = None):
  365. r"""Actions selection
  366. It is displayed as a group of buttons on the page. After the user clicks the button of it,
  367. it will behave differently depending on the type of the button.
  368. :param list buttons: list of buttons. The available formats of the list items are:
  369. * dict::
  370. {
  371. "label":(str) button label,
  372. "value":(object) button value,
  373. "type":(str, optional) button type,
  374. "disabled":(bool, optional) whether the button is disabled,
  375. "color":(str, optional) button color
  376. }
  377. When ``type='reset'/'cancel'`` or ``disabled=True``, ``value`` can be omitted
  378. * tuple or list: ``(label, value, [type], [disabled])``
  379. * single value: label and value of button use the same value
  380. The ``value`` of button can be any JSON serializable object.
  381. ``type`` can be:
  382. * ``'submit'`` : After clicking the button, the entire form is submitted immediately,
  383. and the value of this input item in the final form is the ``value`` of the button that was clicked.
  384. ``'submit'`` is the default value of ``type``
  385. * ``'cancel'`` : Cancel form. After clicking the button, the entire form will be submitted immediately,
  386. and the form value will return ``None``
  387. * ``'reset'`` : Reset form. After clicking the button, the entire form will be reset,
  388. and the input items will become the initial state.
  389. Note: After clicking the ``type=reset`` button, the form will not be submitted,
  390. and the ``actions()`` call will not return
  391. The ``color`` of button can be one of: `primary`, `secondary`, `success`, `danger`, `warning`, `info`, `light`,
  392. `dark`.
  393. :param - label, name, help_text: Those arguments have the same meaning as for `input()`
  394. :return: If the user clicks the ``type=submit`` button to submit the form,
  395. return the value of the button clicked by the user.
  396. If the user clicks the ``type=cancel`` button or submits the form by other means, ``None`` is returned.
  397. When ``actions()`` is used as the last input item in `input_group()` and contains a button with ``type='submit'``,
  398. the default submit button of the `input_group()` form will be replace with the current ``actions()``
  399. **usage scenes of actions() **
  400. .. _custom_form_ctrl_btn:
  401. * Perform simple selection operations:
  402. .. exportable-codeblock::
  403. :name: actions-select
  404. :summary: Use `actions()` to perform simple selection
  405. confirm = actions('Confirm to delete file?', ['confirm', 'cancel'],
  406. help_text='Unrecoverable after file deletion')
  407. if confirm=='confirm': # ..doc-only
  408. ... # ..doc-only
  409. put_markdown('You clicked the `%s` button' % confirm) # ..demo-only
  410. Compared with other input items, when using `actions()`, the user only needs to click once to complete the submission.
  411. * Replace the default submit button:
  412. .. exportable-codeblock::
  413. :name: actions-submit
  414. :summary: Use `actions()` to replace the default submit button
  415. import json # ..demo-only
  416. # ..demo-only
  417. info = input_group('Add user', [
  418. input('username', type=TEXT, name='username', required=True),
  419. input('password', type=PASSWORD, name='password', required=True),
  420. actions('actions', [
  421. {'label': 'Save', 'value': 'save'},
  422. {'label': 'Save and add next', 'value': 'save_and_continue'},
  423. {'label': 'Reset', 'type': 'reset', 'color': 'warning'},
  424. {'label': 'Cancel', 'type': 'cancel', 'color': 'danger'},
  425. ], name='action', help_text='actions'),
  426. ])
  427. put_code('info = ' + json.dumps(info, indent=4))
  428. if info is not None:
  429. save_user(info['username'], info['password']) # ..doc-only
  430. if info['action'] == 'save_and_continue':
  431. add_next() # ..doc-only
  432. put_text('Save and add next...') # ..demo-only
  433. """
  434. assert buttons is not None, 'Required `buttons` parameter in actions()'
  435. item_spec, valid_func, onchange_func = _parse_args(locals())
  436. item_spec['type'] = 'actions'
  437. item_spec['buttons'] = _parse_action_buttons(buttons)
  438. return single_input(item_spec, valid_func, lambda d: d, onchange_func)
  439. def file_upload(label: str = '', accept: Union[List, str] = None, name: str = None, placeholder: str = 'Choose file',
  440. multiple: bool = False, max_size: Union[int, str] = 0, max_total_size: Union[int, str] = 0,
  441. required: bool = None, help_text: str = None, **other_html_attrs):
  442. r"""File uploading
  443. :param accept: Single value or list, indicating acceptable file types. The available formats of file types are:
  444. * A valid case-insensitive filename extension, starting with a period (".") character. For example: ``.jpg``, ``.pdf``, or ``.doc``.
  445. * A valid MIME type string, with no extensions.
  446. For examples: ``application/pdf``, ``audio/*``, ``video/*``, ``image/*``.
  447. For more information, please visit: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
  448. :type accept: str or list
  449. :param str placeholder: A hint to the user of what to be uploaded. It will appear in the input field when there is no file selected.
  450. :param bool multiple: Whether to allow upload multiple files. Default is ``False``.
  451. :param int/str max_size: The maximum size of a single file, exceeding the limit will prohibit uploading.
  452. The default is 0, which means there is no limit to the size.
  453. ``max_size`` can be a integer indicating the number of bytes, or a case-insensitive string ending with `K` / `M` / `G`
  454. (representing kilobytes, megabytes, and gigabytes, respectively).
  455. E.g: ``max_size=500``, ``max_size='40K'``, ``max_size='3M'``
  456. :param int/str max_total_size: The maximum size of all files. Only available when ``multiple=True``.
  457. The default is 0, which means there is no limit to the size. The format is the same as the ``max_size`` parameter
  458. :param bool required: Indicates whether the user must specify a file for the input. Default is ``False``.
  459. :param - label, name, help_text, other_html_attrs: Those arguments have the same meaning as for `input()`
  460. :return: When ``multiple=False``, a dict is returned::
  461. {
  462. 'filename': file name,
  463. 'content':content of the file (in bytes),
  464. 'mime_type': MIME type of the file,
  465. 'last_modified': Last modified time (timestamp) of the file
  466. }
  467. If there is no file uploaded, return ``None``.
  468. When ``multiple=True``, a list is returned. The format of the list item is the same as the return value when ``multiple=False`` above.
  469. If the user does not upload a file, an empty list is returned.
  470. .. note::
  471. If uploading large files, please pay attention to the file upload size limit setting of the web framework.
  472. When using :func:`start_server() <pywebio.platform.tornado.start_server>` or
  473. :func:`path_deploy() <pywebio.platform.path_deploy>` to start the PyWebIO application,
  474. the maximum file size to be uploaded allowed by the web framework can be set through the ``max_payload_size`` parameter.
  475. .. exportable-codeblock::
  476. :name: file_upload_example
  477. :summary: `file_upload()` example
  478. # Upload a file and save to server # ..doc-only
  479. f = input.file_upload("Upload a file") # ..doc-only
  480. open('asset/'+f['filename'], 'wb').write(f['content']) # ..doc-only
  481. imgs = file_upload("Select some pictures:", accept="image/*", multiple=True)
  482. for img in imgs:
  483. put_image(img['content'])
  484. """
  485. item_spec, valid_func, onchange_func = _parse_args(locals())
  486. item_spec['type'] = 'file'
  487. item_spec['max_size'] = parse_file_size(max_size) or platform_setting.MAX_PAYLOAD_SIZE
  488. item_spec['max_total_size'] = parse_file_size(max_total_size) or platform_setting.MAX_PAYLOAD_SIZE
  489. if platform_setting.MAX_PAYLOAD_SIZE:
  490. if item_spec['max_size'] > platform_setting.MAX_PAYLOAD_SIZE or \
  491. item_spec['max_total_size'] > platform_setting.MAX_PAYLOAD_SIZE:
  492. raise ValueError('The `max_size` and `max_total_size` value can not exceed the backend payload size limit. '
  493. 'Please increase the `max_total_size` of `start_server()`/`path_deploy()`')
  494. return single_input(item_spec, valid_func, lambda d: d, onchange_func)
  495. def slider(label: str = '', *, name: str = None, value: Union[int, float] = 0, min_value: Union[int, float] = 0,
  496. max_value: Union[int, float] = 100, step: int = 1, validate: Callable[[Any], Optional[str]] = None,
  497. onchange: Callable[[Any], None] = None, required: bool = None, help_text: str = None, **other_html_attrs):
  498. r"""Range input.
  499. :param int/float value: The initial value of the slider.
  500. :param int/float min_value: The minimum permitted value.
  501. :param int/float max_value: The maximum permitted value.
  502. :param int step: The stepping interval.
  503. Only available when ``value``, ``min_value`` and ``max_value`` are all integer.
  504. :param - label, name, validate, onchange, required, help_text, other_html_attrs: Those arguments have the same meaning as for `input()`
  505. :return int/float: If one of ``value``, ``min_value`` and ``max_value`` is float,
  506. the return value is a float, otherwise an int is returned.
  507. """
  508. item_spec, valid_func, onchange_func = _parse_args(locals())
  509. item_spec['type'] = 'slider'
  510. item_spec['float'] = any(isinstance(i, float) for i in (value, min_value, max_value))
  511. if item_spec['float']:
  512. item_spec['step'] = 'any'
  513. return single_input(item_spec, valid_func, lambda d: d, onchange_func)
  514. def input_group(label: str = '', inputs: List = None, validate: Callable[[Dict], Optional[Tuple[str, str]]] = None,
  515. cancelable: bool = False):
  516. r"""Input group. Request a set of inputs from the user at once.
  517. :param str label: Label of input group.
  518. :param list inputs: Input items.
  519. The item of the list is the call to the single input function, and the ``name`` parameter need to be passed in the single input function.
  520. :param callable validate: validation function for the group. If provided, the validation function will be called when the user submits the form.
  521. Function signature: ``callback(data) -> (name, error_msg)``.
  522. ``validate`` receives the value of the entire group as a parameter. When the form value is valid, it returns ``None``.
  523. When an input item's value is invalid, it returns the ``name`` value of the item and an error message.
  524. For example:
  525. .. exportable-codeblock::
  526. :name: input_group-valid_func
  527. :summary: `input_group()` form validation
  528. def check_form(data):
  529. if len(data['name']) > 6:
  530. return ('name', 'Name to long!')
  531. if data['age'] <= 0:
  532. return ('age', 'Age cannot be negative!')
  533. data = input_group("Basic info",[
  534. input('Input your name', name='name'),
  535. input('Repeat your age', name='age', type=NUMBER)
  536. ], validate=check_form)
  537. put_text(data['name'], data['age'])
  538. :param bool cancelable: Whether the form can be cancelled. Default is ``False``.
  539. If ``cancelable=True``, a "Cancel" button will be displayed at the bottom of the form.
  540. Note: If the last input item in the group is `actions()`, ``cancelable`` will be ignored.
  541. :return: If the user cancels the form, return ``None``, otherwise a ``dict`` is returned,
  542. whose key is the ``name`` of the input item, and whose value is the value of the input item.
  543. """
  544. assert inputs is not None, 'Required `inputs` parameter in input_group()'
  545. spec_inputs = []
  546. preprocess_funcs = {}
  547. item_valid_funcs = {}
  548. onchange_funcs = {}
  549. for single_input_return in inputs:
  550. input_kwargs = single_input_kwargs(single_input_return)
  551. assert all(
  552. k in (input_kwargs or {})
  553. for k in ('item_spec', 'preprocess_func', 'valid_func', 'onchange_func')
  554. ), "`inputs` value error in `input_group`. Did you forget to add `name` parameter in input function?"
  555. input_name = input_kwargs['item_spec']['name']
  556. assert input_name, "`name` can not be empty!"
  557. if input_name in preprocess_funcs:
  558. raise ValueError('Duplicated input item name "%s" in same input group!' % input_name)
  559. preprocess_funcs[input_name] = input_kwargs['preprocess_func']
  560. item_valid_funcs[input_name] = input_kwargs['valid_func']
  561. onchange_funcs[input_name] = input_kwargs['onchange_func']
  562. spec_inputs.append(input_kwargs['item_spec'])
  563. if all('auto_focus' not in i for i in spec_inputs): # No `auto_focus` parameter is set for each input item
  564. for i in spec_inputs:
  565. text_inputs = {TEXT, NUMBER, PASSWORD, SELECT, URL, FLOAT, DATE, TIME, DATETIME_LOCAL}
  566. if i.get('type') in text_inputs:
  567. i['auto_focus'] = True
  568. break
  569. spec = dict(label=label, inputs=spec_inputs, cancelable=cancelable)
  570. return input_control(spec, preprocess_funcs=preprocess_funcs,
  571. item_valid_funcs=item_valid_funcs,
  572. onchange_funcs=onchange_funcs,
  573. form_valid_funcs=validate)
  574. def parse_input_update_spec(spec):
  575. for key in spec:
  576. assert key not in {'action', 'buttons', 'code', 'inline', 'max_size', 'max_total_size', 'multiple', 'name',
  577. 'onchange', 'type', 'validate'}, '%r can not be updated' % key
  578. attributes = dict((k, v) for k, v in spec.items() if v is not None)
  579. if 'options' in spec:
  580. attributes['options'] = _parse_select_options(spec['options'])
  581. return attributes
  582. def input_update(name: str = None, **spec):
  583. """Update attributes of input field.
  584. This function can only be called in ``onchange`` callback of input functions.
  585. :param str name: The ``name`` of the target input item.
  586. Optional, default is the name of input field which triggers ``onchange``
  587. :param spec: The input parameters need to be updated.
  588. Note that those parameters can not be updated:
  589. ``type``, ``name``, ``validate``, ``action``, ``code``, ``onchange``, ``multiple``
  590. An example of implementing dependent input items in an input group:
  591. .. exportable-codeblock::
  592. :name: input-update
  593. :summary: Dependent input items in input group
  594. country2city = {
  595. 'China': ['Beijing', 'Shanghai', 'Hong Kong'],
  596. 'USA': ['New York', 'Los Angeles', 'San Francisco'],
  597. }
  598. countries = list(country2city.keys())
  599. location = input_group("Select a location", [
  600. select('Country', options=countries, name='country',
  601. onchange=lambda c: input_update('city', options=country2city[c])),
  602. select('City', options=country2city[countries[0]], name='city'),
  603. ])
  604. put_text(location) # ..demo-only
  605. """
  606. task_id = get_current_task_id()
  607. k = 'onchange_trigger-' + task_id
  608. if k not in get_current_session().internal_save:
  609. raise RuntimeError("`input_update()` can only be called in `onchange` callback.")
  610. trigger_name = get_current_session().internal_save[k]
  611. if name is None:
  612. name = trigger_name
  613. attributes = parse_input_update_spec(spec)
  614. send_msg('update_input', dict(target_name=name, attributes=attributes))