input.py 34 KB

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