input_usage.py 9.0 KB

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