input.py 30 KB

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