input.py 35 KB

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