input.py 34 KB

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