1
0

input.py 34 KB

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