input_usage.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. """
  2. Input demo
  3. ^^^^^^^^^^^^^^^
  4. Demonstrate various input usage supported by PyWebIO
  5. :demo_host:`Demo </input_usage>`, `Source code <https://github.com/wang0618/PyWebIO/blob/dev/demos/input_usage.py>`_
  6. """
  7. import json
  8. from pywebio import start_server
  9. from pywebio.input import *
  10. from pywebio.output import *
  11. from pywebio.session import set_env, info as session_info
  12. def t(eng, chinese):
  13. """return English or Chinese text according to the user's browser language"""
  14. return chinese if 'zh' in session_info.user_language else eng
  15. def main():
  16. """PyWebIO Input Usage
  17. Demonstrate various input usage supported by PyWebIO.
  18. 演示PyWebIO输入模块的使用
  19. """
  20. set_env(auto_scroll_bottom=True)
  21. put_markdown(t("""# PyWebIO Input Example
  22. You can get the source code of this demo in [here](https://github.com/wang0618/PyWebIO/blob/dev/demos/input_usage.py)
  23. This demo only introduces part of the functions of the PyWebIO input module. For the complete features, please refer to the [User Guide](https://pywebio.readthedocs.io/zh_CN/latest/guide.html).
  24. The input functions are all defined in the `pywebio.input` module and can be imported using `from pywebio.input import *`.
  25. ### Basic input
  26. Here are some basic types of input.
  27. #### Text input
  28. ```python
  29. name = input("What's your name?")
  30. ```
  31. """,
  32. """# PyWebIO 输入演示
  33. 在[这里](https://github.com/wang0618/PyWebIO/blob/dev/demos/input_usage.py)可以获取本Demo的源码。
  34. 本Demo仅提供了PyWebIO输入模块的部分功能的演示,完整特性请参阅[用户指南](https://pywebio.readthedocs.io/zh_CN/latest/guide.html)。
  35. PyWebIO的输入函数都定义在 `pywebio.input` 模块中,可以使用 `from pywebio.input import *` 引入。
  36. ### 基本输入
  37. 首先是一些基本类型的输入
  38. #### 文本输入
  39. ```python
  40. name = input("What's your name?")
  41. ```
  42. """), lstrip=True)
  43. put_text(t("The results of the above example are as follows:", "这样一行代码的效果如下:"))
  44. name = input("What's your name?")
  45. put_markdown("`name = %r`" % name)
  46. # 其他类型的输入
  47. put_markdown(t("""
  48. PyWebIO’s input functions is blocking and will not return until the form is successfully submitted.
  49. #### Other types of input
  50. Here are some other types of input functions:
  51. ```python
  52. # Password input
  53. password = input("Input password", type=PASSWORD)
  54. # Drop-down selection
  55. gift = select('Which gift you want?', ['keyboard', 'ipad'])
  56. # CheckBox
  57. agree = checkbox("User Term", options=['I agree to terms and conditions'])
  58. # Text Area
  59. text = textarea('Text Area', rows=3, placeholder='Some text')
  60. # File Upload
  61. img = file_upload("Select a image:", accept="image/*")
  62. ```
  63. """, """
  64. PyWebIO的输入函数是同步的,在表单被提交之前,输入函数不会返回。
  65. #### 其他类型的输入:
  66. ```python
  67. # 密码输入
  68. password = input("Input password", type=PASSWORD)
  69. # 下拉选择框
  70. gift = select('Which gift you want?', ['keyboard', 'ipad'])
  71. # CheckBox
  72. agree = checkbox("用户协议", options=['I agree to terms and conditions'])
  73. # Text Area
  74. text = textarea('Text Area', rows=3, placeholder='Some text')
  75. # 文件上传
  76. img = file_upload("Select a image:", accept="image/*")
  77. ```
  78. """), lstrip=True)
  79. password = input("Input password", type=PASSWORD)
  80. put_markdown("`password = %r`" % password)
  81. gift = select('Which gift you want?', ['keyboard', 'ipad'])
  82. put_markdown("`gift = %r`" % gift)
  83. agree = checkbox(t("User Term", "用户协议"), options=['I agree to terms and conditions'])
  84. put_markdown("`agree = %r`" % agree)
  85. text = textarea('Text Area', rows=3, placeholder='Some text')
  86. put_markdown("`text = %r`" % text)
  87. img = file_upload("Select a image:", accept="image/*", help_text=t('You can just click "Submit" button', '可以直接选择"提交"'))
  88. if img is None:
  89. put_markdown("`img = %r`" % img)
  90. else:
  91. img['content'] = '...'
  92. img.pop('dataurl', None)
  93. put_code(json.dumps(img, indent=4, ensure_ascii=False).replace('"..."', '...'), 'json')
  94. # 输入选项
  95. put_markdown(t("""#### Parameter of input functions
  96. There are many parameters that can be passed to the input function:
  97. """, """#### 输入选项
  98. 输入函数可指定的参数非常丰富:
  99. """), strip_indent=4)
  100. put_markdown("""
  101. ```python
  102. input('This is label', type=TEXT, placeholder='This is placeholder',
  103. help_text='This is help text', required=True,
  104. datalist=['candidate1', 'candidate2', 'candidate2'])
  105. ```
  106. """, strip_indent=4)
  107. input('This is label', type=TEXT, placeholder='This is placeholder',
  108. help_text='This is help text', required=True,
  109. datalist=['candidate1', 'candidate2', 'candidate2'])
  110. # 校验函数
  111. put_markdown(t("""You can specify a validation function for the input by using `validate` parameter. The validation function should return `None` when the check passes, otherwise an error message will be returned:""", """我们可以为输入指定校验函数,校验函数校验通过时返回`None`,否则返回错误消息:"""), strip_indent=4)
  112. put_markdown("""
  113. ```python
  114. def check_age(p): # return None when the check passes, otherwise return the error message
  115. if p < 10:
  116. return 'Too young!!'
  117. if p > 60:
  118. return 'Too old!!'
  119. age = input("How old are you?", type=NUMBER, validate=check_age)
  120. ```
  121. """, strip_indent=4)
  122. def check_age(p): # 检验函数校验通过时返回None,否则返回错误消息
  123. if p < 10:
  124. return 'Too young!!'
  125. if p > 60:
  126. return 'Too old!!'
  127. age = input("How old are you?", type=NUMBER, validate=check_age, help_text=t('Try to input some illegal values, such as "8", "65"','尝试输入一些非法值,比如"8"、"65"'))
  128. put_markdown('`age = %r`' % age)
  129. # Codemirror
  130. put_markdown(t("""You can use `code` parameter in `pywebio.input.textarea()` to create a code editing textarea:""", """PyWebIO 的 `textarea()` 输入函数还支持使用 [Codemirror](https://codemirror.net/) 实现代码风格的编辑区,只需使用 `code` 参数传入Codemirror支持的选项即可(最简单的情况是直接传入` code={}` 或 `code=True`):"""), strip_indent=4)
  131. put_markdown(r"""
  132. ```python
  133. code = textarea('Code Edit', code={
  134. 'mode': "python", # code language
  135. 'theme': 'darcula', # Codemirror theme
  136. }, value='import something\n# Write your python code')
  137. ```
  138. """, strip_indent=4)
  139. code = textarea('Code Edit', code={
  140. 'mode': "python", # 编辑区代码语言
  141. 'theme': 'darcula', # 编辑区darcula主题, Visit https://codemirror.net/demo/theme.html#cobalt to get more themes
  142. }, value='import something\n# Write your python code')
  143. put_markdown("Your code:\n```python\n%s\n```" % code)
  144. # 输入组
  145. put_markdown(t("""### Input Group
  146. `input_group()` accepts a list of single input function call as parameter, and returns a dictionary with the name of the single input function as the key and the input data as the value.
  147. The input group also supports using `validate` parameter to set the validation function, which accepts the entire form data as parameter:""",
  148. """### 输入组
  149. `input_group()` 接受单项输入组成的列表作为参数,输入组中需要在每一项输入函数中提供 `name` 参数来用于在结果中标识不同输入项。输入组中同样支持设置校验函数,其接受整个表单数据作为参数。检验函数校验通过时返回None,否则返回 `(input name,错误消息)`
  150. """), strip_indent=4)
  151. put_markdown(r"""
  152. ```python
  153. def check_form(data): # input group validation: return (input name, error msg) when validation fail
  154. if len(data['name']) > 6:
  155. return ('name', 'Name too long!')
  156. if data['age'] <= 0:
  157. return ('age', 'Age can not be negative!')
  158. data = input_group("Basic info", [
  159. input('Input your name', name='name'),
  160. input('Input your age', name='age', type=NUMBER, validate=check_age)
  161. ], validate=check_form)
  162. ```
  163. """, strip_indent=4)
  164. def check_form(data): # input group validation: return (input name, error msg) when validation fail
  165. if len(data['name']) > 6:
  166. return ('name', 'Name too long!')
  167. if data['age'] <= 0:
  168. return ('age', 'Age can not be negative!')
  169. data = input_group("Basic info", [
  170. input('Input your name', name='name'),
  171. input('Input your age', name='age', type=NUMBER, validate=check_age)
  172. ], validate=check_form)
  173. put_markdown("`data = %r`" % data)
  174. put_markdown(t("""----
  175. For more information about input of PyWebIO, please visit PyWebIO [User Guide](https://pywebio.readthedocs.io/zh_CN/latest/guide.html) and [input module documentation](https://pywebio.readthedocs.io/zh_CN/latest/input.html).
  176. """, """----
  177. PyWebIO的输入演示到这里就结束了,更多内容请访问PyWebIO[用户指南](https://pywebio.readthedocs.io/zh_CN/latest/guide.html)和[input模块文档](https://pywebio.readthedocs.io/zh_CN/latest/input.html)。
  178. """), lstrip=True)
  179. if __name__ == '__main__':
  180. start_server(main, debug=True, port=8080, cdn=False)