input.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. """从浏览器接收用户输入
  2. 本模块提供了一系列函数来从浏览器接收用户不同的形式的输入
  3. 输入函数大致分为两类,一类是单项输入::
  4. name = input("What's your name")
  5. print("Your name is %s" % name)
  6. 另一类是使用 `input_group` 的输入组::
  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. 输入组中需要在每一项输入函数中提供 ``name`` 参数来用于在结果中标识不同输入项.
  13. .. note::
  14. PyWebIO 根据是否在输入函数中传入 ``name`` 参数来判断输入函数是在 `input_group` 中还是被单独调用。
  15. 所以当你想要单独调用一个输入函数时,请不要设置 ``name`` 参数;而在 `input_group` 中调用输入函数时,**务必提供** ``name`` 参数
  16. """
  17. import logging
  18. from base64 import b64decode
  19. from collections.abc import Mapping
  20. from typing import Coroutine
  21. from .io_ctrl import single_input, input_control
  22. logger = logging.getLogger(__name__)
  23. TEXT = 'text'
  24. NUMBER = "number"
  25. FLOAT = "float"
  26. PASSWORD = "password"
  27. CHECKBOX = 'checkbox'
  28. RADIO = 'radio'
  29. SELECT = 'select'
  30. TEXTAREA = 'textarea'
  31. __all__ = ['TEXT', 'NUMBER', 'FLOAT', 'PASSWORD', 'CHECKBOX', 'RADIO', 'SELECT', 'TEXTAREA',
  32. 'input', 'textarea', 'select', 'checkbox', 'radio', 'actions', 'file_upload', 'input_group']
  33. def _parse_args(kwargs):
  34. """处理传给各类输入函数的原始参数,
  35. :return:(spec参数,valid_func)
  36. """
  37. # 对为None的参数忽略处理
  38. kwargs = {k: v for k, v in kwargs.items() if v is not None}
  39. kwargs.update(kwargs.get('other_html_attrs', {}))
  40. kwargs.pop('other_html_attrs', None)
  41. valid_func = kwargs.pop('valid_func', lambda _: None)
  42. return kwargs, valid_func
  43. def input(label, type=TEXT, *, valid_func=None, name=None, value=None, placeholder=None, required=None,
  44. readonly=None, help_text=None, **other_html_attrs) -> Coroutine:
  45. r"""文本输入
  46. :param str label: 输入框标签
  47. :param str type: 输入类型. 可使用的常量:`TEXT` , `NUMBER` , `FLOAT`, `PASSWORD` , `TEXTAREA`
  48. :param Callable valid_func: 输入值校验函数. 如果提供,当用户输入完毕或提交表单后校验函数将被调用.
  49. ``valid_func`` 接收输入值作为参数,当输入值有效时,返回 ``None`` ,当输入值无效时,返回错误提示字符串. 比如::
  50. def check_age(age):
  51. if age>30:
  52. return 'Too old'
  53. elif age<10:
  54. return 'Too young'
  55. await input('Input your age', type=NUMBER, valid_func=check_age)
  56. :param name: 输入框的名字. 与 `input_group` 配合使用,用于在输入组的结果中标识不同输入项. **在单个输入中,不可以设置该参数!**
  57. :param str value: 输入框的初始值
  58. :param str placeholder: 输入框的提示内容。提示内容会在输入框未输入值时以浅色字体显示在输入框中
  59. :param bool required: 当前输入是否为必填项
  60. :param bool readonly: 输入框是否为只读
  61. :param str help_text: 输入框的帮助文本。帮助文本会以小号字体显示在输入框下方
  62. :param other_html_attrs: 在输入框上附加的额外html属性。参考: https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/input#%E5%B1%9E%E6%80%A7
  63. :return: 用户输入的值
  64. """
  65. item_spec, valid_func = _parse_args(locals())
  66. # 参数检查
  67. allowed_type = {TEXT, NUMBER, FLOAT, PASSWORD, TEXTAREA}
  68. assert type in allowed_type, 'Input type not allowed.'
  69. def preprocess_func(d):
  70. if type == NUMBER:
  71. d = int(d)
  72. elif type == FLOAT:
  73. d = float(d)
  74. return d
  75. if type == FLOAT:
  76. item_spec['type'] = TEXT
  77. return single_input(item_spec, valid_func, preprocess_func)
  78. def textarea(label, rows=6, *, code=None, maxlength=None, minlength=None, valid_func=None, name=None, value=None,
  79. placeholder=None, required=None, readonly=None, help_text=None, **other_html_attrs):
  80. r"""文本输入域
  81. :param int rows: 输入文本的行数(显示的高度)。输入的文本超出设定值时会显示滚动条
  82. :param int maxlength: 允许用户输入的最大字符长度 (Unicode) 。未指定表示无限长度
  83. :param int minlength: 允许用户输入的最小字符长度(Unicode)
  84. :param dict code: 通过提供 `Codemirror <https://codemirror.net/>`_ 参数让文本输入域具有代码编辑器样式::
  85. res = await textarea('Text area', code={
  86. 'mode': "python",
  87. 'theme': 'darcula'
  88. })
  89. 更多配置可以参考 https://codemirror.net/doc/manual.html#config
  90. :param - label, valid_func, name, value, placeholder, required, readonly, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
  91. :return: 用户输入的文本
  92. """
  93. item_spec, valid_func = _parse_args(locals())
  94. item_spec['type'] = TEXTAREA
  95. return single_input(item_spec, valid_func, lambda d: d)
  96. def _parse_select_options(options):
  97. # 转换 select、checkbox、radio函数中的 options 参数为统一的格式
  98. # option 可用形式:
  99. # {value:, label:, [selected:,] [disabled:]}
  100. # (value, label, [selected,] [disabled])
  101. # value 单值,label等于value
  102. opts_res = []
  103. for opt in options:
  104. if isinstance(opt, Mapping):
  105. assert 'value' in opt and 'label' in opt, 'options item must have value and label key'
  106. elif isinstance(opt, (list, tuple)):
  107. assert len(opt) > 1 and len(opt) <= 4, 'options item format error'
  108. opt = dict(zip(('label', 'value', 'selected', 'disabled'), opt))
  109. else:
  110. opt = dict(value=opt, label=opt)
  111. opt['value'] = str(opt['value'])
  112. opts_res.append(opt)
  113. return opts_res
  114. def _set_options_selected(options, value):
  115. """使用value为options的项设置selected"""
  116. if not isinstance(value, (list, tuple)):
  117. value = [value]
  118. for opt in options:
  119. if opt['value'] in value:
  120. opt['selected'] = True
  121. return options
  122. def select(label, options, *, multiple=None, valid_func=None, name=None, value=None, required=None,
  123. help_text=None, **other_html_attrs):
  124. r"""下拉选择框。默认单选,设置 multiple 参数后,可以多选。但都至少要选择一个选项。
  125. :param list options: 可选项列表。列表项的可用形式有:
  126. * dict: ``{label:选项标签, value: 选项值, [selected:是否默认选中,] [disabled:是否禁止选中]}``
  127. * tuple or list: ``(label, value, [selected,] [disabled])``
  128. * 单值: 此时label和value使用相同的值
  129. 注意:
  130. 1. options 中的 value 最终会转换成字符串。 select 返回值也是字符串(或字符串列表)
  131. 2. 若 ``multiple`` 选项不为 ``True`` 则可选项列表最多仅能有一项的 ``selected`` 为 ``True``。
  132. :param multiple: 是否可以多选. 默认单选
  133. :param value: 下拉选择框初始选中项的值。当 ``multiple=True`` 时, ``value`` 需为list,否则为单个选项的值。
  134. 你也可以通过设置 ``options`` 列表项中的 ``selected`` 字段来设置默认选中选项。
  135. :type value: list or str
  136. :param bool required: 是否至少选择一项
  137. :param - label, valid_func, name, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
  138. :return: 字符串/字符串列表。如果 ``multiple=True`` 时,返回用户选中的 options 中的值的列表;不设置 ``multiple`` 时,返回用户选中的 options 中的值
  139. """
  140. item_spec, valid_func = _parse_args(locals())
  141. item_spec['options'] = _parse_select_options(options)
  142. if value is not None:
  143. del item_spec['value']
  144. item_spec['options'] = _set_options_selected(item_spec['options'], value)
  145. item_spec['type'] = SELECT
  146. return single_input(item_spec, valid_func, lambda d: d)
  147. def checkbox(label, options, *, inline=None, valid_func=None, name=None, value=None, help_text=None,
  148. **other_html_attrs):
  149. r"""勾选选项。可以多选,也可以不选。
  150. :param list options: 可选项列表。格式与 `select` 函数的 ``options`` 参数含义一致
  151. :param bool inline: 是否将选项显示在一行上。默认每个选项单独占一行
  152. :param list value: 勾选选项初始选中项。为选项值的列表。
  153. 你也可以通过设置 ``options`` 列表项中的 ``selected`` 字段来设置默认选中选项。
  154. :param - label, valid_func, name, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
  155. :return: 用户选中的 options 中的值的列表。当用户没有勾选任何选项时,返回空列表
  156. """
  157. item_spec, valid_func = _parse_args(locals())
  158. item_spec['options'] = _parse_select_options(options)
  159. if value is not None:
  160. del item_spec['value']
  161. item_spec['options'] = _set_options_selected(item_spec['options'], value)
  162. item_spec['type'] = CHECKBOX
  163. return single_input(item_spec, valid_func, lambda d: d)
  164. def radio(label, options, *, inline=None, valid_func=None, name=None, value=None, required=None,
  165. help_text=None, **other_html_attrs):
  166. r"""单选选项
  167. :param list options: 可选项列表。格式与 `select` 函数的 ``options`` 参数含义一致
  168. :param bool inline: 是否将选项显示在一行上。默认每个选项单独占一行
  169. :param str value: 单选选项初始选中项的值。
  170. 你也可以通过设置 ``options`` 列表项中的 ``selected`` 字段来设置默认选中选项。
  171. :param bool required: 是否至少选择一项
  172. :param - label, valid_func, name, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
  173. :return: 用户选中的选项的值(字符串)
  174. """
  175. item_spec, valid_func = _parse_args(locals())
  176. item_spec['options'] = _parse_select_options(options)
  177. if value is not None:
  178. del item_spec['value']
  179. item_spec['options'] = _set_options_selected(item_spec['options'], value)
  180. if required is not None:
  181. del item_spec['required']
  182. item_spec['options'][-1]['required'] = required
  183. item_spec['type'] = RADIO
  184. return single_input(item_spec, valid_func, lambda d: d)
  185. def _parse_action_buttons(buttons):
  186. """
  187. :param label:
  188. :param actions: action 列表
  189. action 可用形式:
  190. {label:, value:, [disabled:]}
  191. (label, value, [disabled])
  192. value 单值,label等于value
  193. :return:
  194. """
  195. act_res = []
  196. for act in buttons:
  197. if isinstance(act, Mapping):
  198. assert 'value' in act and 'label' in act, 'actions item must have value and label key'
  199. elif isinstance(act, (list, tuple)):
  200. assert len(act) in (2, 3), 'actions item format error'
  201. act = dict(zip(('label', 'value', 'disabled'), act))
  202. else:
  203. act = dict(value=act, label=act)
  204. act_res.append(act)
  205. return act_res
  206. def actions(label, buttons, name=None, help_text=None):
  207. r"""按钮选项。
  208. 在浏览器上显示为一组按钮,与其他输入组件不同,用户点击按钮后会立即将整个表单提交,而其他输入组件则需要手动点击表单的"提交"按钮。
  209. 当 ``actions()`` 作为 `input_group()` 的 ``inputs`` 中最后一个输入项时,表单默认的提交按钮会被当前 ``actions()`` 替换。
  210. :param list buttons: 选项列表。列表项的可用形式有:
  211. * dict: ``{label:选项标签, value:选项值, [disabled:是否禁止选择]}``
  212. * tuple or list: ``(label, value, [disabled])``
  213. * 单值: 此时label和value使用相同的值
  214. :param - label, name, help_text: 与 `input` 输入函数的同名参数含义一致
  215. :return: 用户点击的按钮的值
  216. """
  217. item_spec, valid_func = _parse_args(locals())
  218. item_spec['type'] = 'actions'
  219. item_spec['buttons'] = _parse_action_buttons(buttons)
  220. return single_input(item_spec, valid_func, lambda d: d)
  221. def file_upload(label, accept=None, name=None, placeholder='Choose file', help_text=None, **other_html_attrs):
  222. r"""文件上传。
  223. :param accept: 单值或列表, 表示可接受的文件类型。单值或列表项支持的形式有:
  224. * 以 ``.`` 字符开始的文件扩展名(例如:``.jpg, .png, .doc``)。
  225. 注意:截止本文档编写之时,微信内置浏览器还不支持这种语法
  226. * 一个有效的 MIME 类型。
  227. 例如: ``application/pdf`` 、 ``audio/*`` 表示音频文件、``video/*`` 表示视频文件、``image/*`` 表示图片文件
  228. 参考 https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
  229. :type accept: str or list
  230. :param - label, name, placeholder, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
  231. :return: 表示用户文件的字典,格式为: ``{'filename': 文件名, 'content':文件二进制数据(bytes object)}``
  232. """
  233. item_spec, valid_func = _parse_args(locals())
  234. item_spec['type'] = 'file'
  235. def read_file(data): # data: {'filename':, 'dataurl'}
  236. header, encoded = data['dataurl'].split(",", 1)
  237. data['content'] = b64decode(encoded)
  238. return data
  239. return single_input(item_spec, valid_func, read_file)
  240. def input_group(label, inputs, valid_func=None):
  241. r"""输入组。向页面上展示一组输入
  242. :param str label: 输入组标签
  243. :param list inputs: 输入项列表。列表的内容为对单项输入函数的调用,并在单项输入函数中传入 ``name`` 参数。
  244. :param Callable valid_func: 输入组校验函数。
  245. 函数签名:``callback(data) -> (name, error_msg)``
  246. ``valid_func`` 接收整个表单的值为参数,当校验表单值有效时,返回 ``None`` ,当某项输入值无效时,返回出错输入项的 ``name`` 值和错误提示. 比如::
  247. def check_form(data):
  248. if len(data['name']) > 6:
  249. return ('name', '名字太长!')
  250. if data['age'] <= 0:
  251. return ('age', '年龄不能为负数!')
  252. data = await input_group("Basic info",[
  253. input('Input your name', name='name'),
  254. input('Repeat your age', name='age', type=NUMBER)
  255. ], valid_func=check_form)
  256. print(data['name'], data['age'])
  257. :return: 返回一个 ``dict`` , 其键为输入项的 ``name`` 值,字典值为输入项的值
  258. """
  259. spec_inputs = []
  260. preprocess_funcs = {}
  261. item_valid_funcs = {}
  262. for single_input_return in inputs:
  263. try:
  264. single_input_return.send(None)
  265. except StopIteration as e:
  266. input_kwargs = e.args[0]
  267. except AttributeError:
  268. input_kwargs = single_input_return
  269. else:
  270. raise RuntimeError("Can't get kwargs from single input")
  271. assert all(k in input_kwargs for k in ('item_spec', 'preprocess_func', 'valid_func')), RuntimeError(
  272. "`inputs` value error in `input_group`. Did you forget to add `name` parameter in input function?")
  273. input_name = input_kwargs['item_spec']['name']
  274. preprocess_funcs[input_name] = input_kwargs['preprocess_func']
  275. item_valid_funcs[input_name] = input_kwargs['valid_func']
  276. spec_inputs.append(input_kwargs['item_spec'])
  277. if all('auto_focus' not in i for i in spec_inputs): # 每一个输入项都没有设置autofocus参数
  278. for i in spec_inputs:
  279. text_inputs = {TEXT, NUMBER, PASSWORD, SELECT} # todo update
  280. if i.get('type') in text_inputs:
  281. i['auto_focus'] = True
  282. break
  283. spec = dict(label=label, inputs=spec_inputs)
  284. return input_control(spec, preprocess_funcs=preprocess_funcs, item_valid_funcs=item_valid_funcs,
  285. form_valid_funcs=valid_func)