input.py 14 KB

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