input.py 33 KB

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