input.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. return single_input(item_spec, valid_func, preprocess_func)
  76. def textarea(label, rows=6, *, code=None, maxlength=None, minlength=None, valid_func=None, name=None, value=None,
  77. placeholder=None, required=None, readonly=None, help_text=None, **other_html_attrs):
  78. r"""文本输入域
  79. :param int rows: 输入文本的行数(显示的高度)。输入的文本超出设定值时会显示滚动条
  80. :param int maxlength: 允许用户输入的最大字符长度 (Unicode) 。未指定表示无限长度
  81. :param int minlength: 允许用户输入的最小字符长度(Unicode)
  82. :param dict code: 通过提供 `Codemirror <https://codemirror.net/>`_ 参数让文本输入域具有代码编辑器样式::
  83. res = await textarea('Text area', code={
  84. 'mode': "python",
  85. 'theme': 'darcula'
  86. })
  87. 更多配置可以参考 https://codemirror.net/doc/manual.html#config
  88. :param - label, valid_func, name, value, placeholder, required, readonly, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
  89. :return: 用户输入的文本
  90. """
  91. item_spec, valid_func = _parse_args(locals())
  92. item_spec['type'] = TEXTAREA
  93. return single_input(item_spec, valid_func, lambda d: d)
  94. def _parse_select_options(options):
  95. # option 可用形式:
  96. # {value:, label:, [selected:,] [disabled:]}
  97. # (value, label, [selected,] [disabled])
  98. # value 单值,label等于value
  99. opts_res = []
  100. for opt in options:
  101. if isinstance(opt, Mapping):
  102. assert 'value' in opt and 'label' in opt, 'options item must have value and label key'
  103. elif isinstance(opt, (list, tuple)):
  104. assert len(opt) > 1 and len(opt) <= 4, 'options item format error'
  105. opt = dict(zip(('label', 'value', 'selected', 'disabled'), opt))
  106. else:
  107. opt = dict(value=opt, label=opt)
  108. opts_res.append(opt)
  109. return opts_res
  110. def select(label, options, *, multiple=None, valid_func=None, name=None, value=None,
  111. required=None, readonly=None, help_text=None, **other_html_attrs):
  112. r"""下拉选择框。默认单选,设置 multiple 参数后,可以多选。但都至少要选择一个选项。
  113. :param list options: 可选项列表。列表项的可用形式有:
  114. * dict: ``{label:选项标签, value: 选项值, [selected:是否默认选中,] [disabled:是否禁止选中]}``
  115. * tuple or list: ``(label, value, [selected,] [disabled])``
  116. * 单值: 此时label和value使用相同的值
  117. 注意:
  118. 1. options 中的 value 最终会转换成字符串。 select 返回值也是字符串(或字符串列表)
  119. 2. 若 ``multiple`` 选项不为 ``True`` 则可选项列表最多仅能有一项的 ``selected`` 为 ``True``。
  120. :param multiple: 是否可以多选. 默认单选
  121. :param - label, valid_func, name, value, required, readonly, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
  122. :return: 字符串/字符串列表。如果 ``multiple=True`` 时,返回用户选中的 options 中的值的列表;不设置 ``multiple`` 时,返回用户选中的 options 中的值
  123. """
  124. item_spec, valid_func = _parse_args(locals())
  125. item_spec['options'] = _parse_select_options(options)
  126. item_spec['type'] = SELECT
  127. return single_input(item_spec, valid_func, lambda d: d)
  128. def checkbox(label, options, *, inline=None, valid_func=None, name=None, value=None,
  129. required=None, readonly=None, help_text=None, **other_html_attrs):
  130. r"""勾选选项。可以多选,也可以不选。
  131. :param list options: 可选项列表。格式与 `select` 函数的 ``options`` 参数含义一致
  132. :param bool inline: 是否将选项显示在一行上。默认每个选项单独占一行
  133. :param - label, valid_func, name, value, required, readonly, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
  134. :return: 用户选中的 options 中的值的列表。当用户没有勾选任何选项时,返回空列表
  135. """
  136. item_spec, valid_func = _parse_args(locals())
  137. item_spec['options'] = _parse_select_options(options)
  138. item_spec['type'] = CHECKBOX
  139. return single_input(item_spec, valid_func, lambda d: d)
  140. def radio(label, options, *, inline=None, valid_func=None, name=None, value=None, required=None,
  141. readonly=None, help_text=None, **other_html_attrs):
  142. r"""单选选项
  143. :param list options: 可选项列表。格式与 `select` 函数的 ``options`` 参数含义一致
  144. :param bool inline: 是否将选项显示在一行上。默认每个选项单独占一行
  145. :param - label, valid_func, name, value, required, readonly, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
  146. :return: 用户选中的选项的值(字符串)
  147. """
  148. item_spec, valid_func = _parse_args(locals())
  149. item_spec['options'] = _parse_select_options(options)
  150. item_spec['type'] = RADIO
  151. return single_input(item_spec, valid_func, lambda d: d)
  152. def _parse_action_buttons(buttons):
  153. """
  154. :param label:
  155. :param actions: action 列表
  156. action 可用形式:
  157. {label:, value:, [disabled:]}
  158. (label, value, [disabled])
  159. value 单值,label等于value
  160. :return:
  161. """
  162. act_res = []
  163. for act in buttons:
  164. if isinstance(act, Mapping):
  165. assert 'value' in act and 'label' in act, 'actions item must have value and label key'
  166. elif isinstance(act, (list, tuple)):
  167. assert len(act) in (2, 3), 'actions item format error'
  168. act = dict(zip(('label', 'value', 'disabled'), act))
  169. else:
  170. act = dict(value=act, label=act)
  171. act_res.append(act)
  172. return act_res
  173. def actions(label, buttons, name=None, help_text=None):
  174. r"""按钮选项。
  175. 在浏览器上显示为一组按钮,与其他输入组件不同,用户点击按钮后会立即将整个表单提交,而其他输入组件则需要手动点击表单的"提交"按钮。
  176. 当 ``actions()`` 作为 `input_group()` 的 ``inputs`` 中最后一个输入项时,表单默认的提交按钮会被当前 ``actions()`` 替换。
  177. :param list buttons: 选项列表。列表项的可用形式有:
  178. * dict: ``{label:选项标签, value:选项值, [disabled:是否禁止选择]}``
  179. * tuple or list: ``(label, value, [disabled])``
  180. * 单值: 此时label和value使用相同的值
  181. :param - label, name, help_text: 与 `input` 输入函数的同名参数含义一致
  182. :return: 用户点击的按钮的值
  183. """
  184. item_spec, valid_func = _parse_args(locals())
  185. item_spec['type'] = 'actions'
  186. item_spec['buttons'] = _parse_action_buttons(buttons)
  187. return single_input(item_spec, valid_func, lambda d: d)
  188. def file_upload(label, accept=None, name=None, placeholder='Choose file', help_text=None, **other_html_attrs):
  189. r"""文件上传。
  190. :param accept: 单值或列表, 表示可接受的文件类型。单值或列表项支持的形式有:
  191. * 以 ``.`` 字符开始的文件扩展名(例如:``.jpg, .png, .doc``)。
  192. 注意:截止本文档编写之时,微信内置浏览器还不支持这种语法
  193. * 一个有效的 MIME 类型。
  194. 例如: ``application/pdf`` 、 ``audio/*`` 表示音频文件、``video/*`` 表示视频文件、``image/*`` 表示图片文件
  195. 参考 https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
  196. :type accept: str or list
  197. :param - label, name, placeholder, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
  198. :return: 表示用户文件的字典,格式为: ``{'filename': 文件名, 'content':文件二进制数据(bytes object)}``
  199. """
  200. item_spec, valid_func = _parse_args(locals())
  201. item_spec['type'] = 'file'
  202. def read_file(data): # data: {'filename':, 'dataurl'}
  203. header, encoded = data['dataurl'].split(",", 1)
  204. data['content'] = b64decode(encoded)
  205. return data
  206. return single_input(item_spec, valid_func, read_file)
  207. def input_group(label, inputs, valid_func=None):
  208. r"""输入组。向页面上展示一组输入
  209. :param str label: 输入组标签
  210. :param list inputs: 输入项列表。列表的内容为对单项输入函数的调用,并在单项输入函数中传入 ``name`` 参数。
  211. :param Callable valid_func: 输入组校验函数。
  212. 函数签名:``callback(data) -> (name, error_msg)``
  213. ``valid_func`` 接收整个表单的值为参数,当校验表单值有效时,返回 ``None`` ,当某项输入值无效时,返回出错输入项的 ``name`` 值和错误提示. 比如::
  214. def check_form(data):
  215. if len(data['name']) > 6:
  216. return ('name', '名字太长!')
  217. if data['age'] <= 0:
  218. return ('age', '年龄不能为负数!')
  219. data = await input_group("Basic info",[
  220. input('Input your name', name='name'),
  221. input('Repeat your age', name='age', type=NUMBER)
  222. ], valid_func=check_form)
  223. print(data['name'], data['age'])
  224. :return: 返回一个 ``dict`` , 其键为输入项的 ``name`` 值,字典值为输入项的值
  225. """
  226. spec_inputs = []
  227. preprocess_funcs = {}
  228. item_valid_funcs = {}
  229. for single_input_return in inputs:
  230. try:
  231. single_input_return.send(None)
  232. except StopIteration as e:
  233. input_kwargs = e.args[0]
  234. except AttributeError:
  235. input_kwargs = single_input_return
  236. else:
  237. raise RuntimeError("Can't get kwargs from single input")
  238. assert all(k in input_kwargs for k in ('item_spec', 'preprocess_func', 'valid_func')), RuntimeError(
  239. "`inputs` value error in `input_group`. Did you forget to add `name` parameter in input function?")
  240. input_name = input_kwargs['item_spec']['name']
  241. preprocess_funcs[input_name] = input_kwargs['preprocess_func']
  242. item_valid_funcs[input_name] = input_kwargs['valid_func']
  243. spec_inputs.append(input_kwargs['item_spec'])
  244. if all('auto_focus' not in i for i in spec_inputs): # 每一个输入项都没有设置autofocus参数
  245. for i in spec_inputs:
  246. text_inputs = {TEXT, NUMBER, PASSWORD, SELECT} # todo update
  247. if i.get('type') in text_inputs:
  248. i['auto_focus'] = True
  249. break
  250. spec = dict(label=label, inputs=spec_inputs)
  251. return input_control(spec, preprocess_funcs=preprocess_funcs, item_valid_funcs=item_valid_funcs,
  252. form_valid_funcs=valid_func)