input.py 35 KB

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