Skip to content

Commit

Permalink
maint: change input functions' parameter 'valid_func' to 'validate'
Browse files Browse the repository at this point in the history
  • Loading branch information
wang0618 committed Jan 3, 2021
1 parent ad73a77 commit 4f5e672
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 46 deletions.
2 changes: 1 addition & 1 deletion demos/chat_room.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ async def main():
本应用使用不到80行代码实现,源代码[链接](https://github.com/wang0618/PyWebIO/blob/master/demos/chat_room.py)""", lstrip=True)

nickname = await input("请输入你的昵称", required=True,
valid_func=lambda n: '昵称已被使用' if n in online_users or n == '📢' else None)
validate=lambda n: '昵称已被使用' if n in online_users or n == '📢' else None)

online_users.add(nickname)
chat_msgs.append(('📢', '`%s`加入聊天室. 当前在线人数 %s' % (nickname, len(online_users))))
Expand Down
12 changes: 6 additions & 6 deletions demos/input_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def check_age(p): # 检验函数校验通过时返回None,否则返回错误
if p > 60:
return 'Too old!!'
age = input("How old are you?", type=NUMBER, valid_func=check_age)
age = input("How old are you?", type=NUMBER, validate=check_age)
```
""", strip_indent=4)

Expand All @@ -95,7 +95,7 @@ def check_age(p): # 检验函数校验通过时返回None,否则返回错误
if p > 60:
return 'Too old!!'

age = input("How old are you?", type=NUMBER, valid_func=check_age, help_text='尝试输入一些非法值,比如"8"、"65"')
age = input("How old are you?", type=NUMBER, validate=check_age, help_text='尝试输入一些非法值,比如"8"、"65"')
put_markdown('`age = %r`' % age)

# Codemirror
Expand Down Expand Up @@ -128,8 +128,8 @@ def check_form(data): # 检验函数校验通过时返回None,否则返回 (i
data = input_group("Basic info", [
input('Input your name', name='name'),
input('Input your age', name='age', type=NUMBER, valid_func=check_age)
], valid_func=check_form)
input('Input your age', name='age', type=NUMBER, validate=check_age)
], validate=check_form)
```
""", strip_indent=4)

Expand All @@ -141,8 +141,8 @@ def check_form(data): # 检验函数校验通过时返回None,否则返回 (i

data = input_group("Basic info", [
input('Input your name', name='name'),
input('Input your age', name='age', type=NUMBER, valid_func=check_age)
], valid_func=check_form)
input('Input your age', name='age', type=NUMBER, validate=check_age)
], validate=check_form)

put_markdown("`data = %r`" % data)

Expand Down
10 changes: 5 additions & 5 deletions docs/guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ User's guide
if p > 60:
return 'Too old!!'

age = input("How old are you?", type=NUMBER, valid_func=check_age)
age = input("How old are you?", type=NUMBER, validate=check_age)
put_text('age = %r' % age) # ..demo-only

当用户输入了不合法的值时,页面上的显示如下:
Expand Down Expand Up @@ -140,11 +140,11 @@ PyWebIO支持输入组, 返回结果为一个字典。`pywebio.input.input_group
# ..demo-only
data = input_group("Basic info",[
input('Input your name', name='name'),
input('Input your age', name='age', type=NUMBER, valid_func=check_age)
input('Input your age', name='age', type=NUMBER, validate=check_age)
])
put_text(data['name'], data['age'])

输入组中同样支持使用 ``valid_func`` 参数设置校验函数,其接受整个表单数据作为参数:
输入组中同样支持使用 ``validate`` 参数设置校验函数,其接受整个表单数据作为参数:

.. exportable-codeblock::
:name: input-group
Expand All @@ -164,8 +164,8 @@ PyWebIO支持输入组, 返回结果为一个字典。`pywebio.input.input_group

data = input_group("Basic info",[ # ..demo-only
input('Input your name', name='name'), # ..demo-only
input('Input your age', name='age', type=NUMBER, valid_func=check_age) # ..demo-only
], valid_func=check_form) # ..demo-only
input('Input your age', name='age', type=NUMBER, validate=check_age) # ..demo-only
], validate=check_form) # ..demo-only
put_text(data['name'], data['age']) # ..demo-only

.. attention::
Expand Down
36 changes: 18 additions & 18 deletions pywebio/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,20 +100,20 @@ def _parse_args(kwargs, excludes=()):
assert is_html_safe_value(kwargs.get('name', '')), '`name` can only contains a-z、A-Z、0-9、_、-'
kwargs.update(kwargs.get('other_html_attrs', {}))
kwargs.pop('other_html_attrs', None)
valid_func = kwargs.pop('valid_func', lambda _: None)
valid_func = kwargs.pop('validate', lambda _: None)
return kwargs, valid_func


def input(label='', type=TEXT, *, valid_func=None, name=None, value=None, action=None, placeholder=None, required=None,
def input(label='', type=TEXT, *, validate=None, name=None, value=None, action=None, placeholder=None, required=None,
readonly=None, datalist=None, help_text=None, **other_html_attrs):
r"""文本输入
:param str label: 输入框标签
:param str type: 输入类型. 可使用的常量:`TEXT` , `NUMBER` , `FLOAT` , `PASSWORD` , `URL` , `DATE` , `TIME`
其中 `DATE` , `TIME` 类型在某些浏览器上不被支持,详情见 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Browser_compatibility
:param Callable valid_func: 输入值校验函数. 如果提供,当用户输入完毕或提交表单后校验函数将被调用.
``valid_func`` 接收输入值作为参数,当输入值有效时,返回 ``None`` ,当输入值无效时,返回错误提示字符串. 比如:
:param Callable validate: 输入值校验函数. 如果提供,当用户输入完毕或提交表单后校验函数将被调用.
``validate`` 接收输入值作为参数,当输入值有效时,返回 ``None`` ,当输入值无效时,返回错误提示字符串. 比如:
.. exportable-codeblock::
:name: input-valid-func
Expand All @@ -124,7 +124,7 @@ def check_age(age):
return 'Too old'
elif age<10:
return 'Too young'
input('Input your age', type=NUMBER, valid_func=check_age)
input('Input your age', type=NUMBER, validate=check_age)
:param name: 输入框的名字. 与 `input_group` 配合使用,用于在输入组的结果中标识不同输入项. **在单个输入中,不可以设置该参数!**
:param str value: 输入框的初始值
Expand Down Expand Up @@ -225,7 +225,7 @@ def preprocess_func(d): # 将用户提交的原始数据进行转换
return single_input(item_spec, valid_func, preprocess_func)


def textarea(label='', *, rows=6, code=None, maxlength=None, minlength=None, valid_func=None, name=None, value=None,
def textarea(label='', *, rows=6, code=None, maxlength=None, minlength=None, validate=None, name=None, value=None,
placeholder=None, required=None, readonly=None, help_text=None, **other_html_attrs):
r"""文本输入域(多行文本输入)
Expand All @@ -245,7 +245,7 @@ def textarea(label='', *, rows=6, code=None, maxlength=None, minlength=None, val
put_code(res, language='python') # ..demo-only
更多配置可以参考 https://codemirror.net/doc/manual.html#config
:param - label, valid_func, name, value, placeholder, required, readonly, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
:param - label, validate, name, value, placeholder, required, readonly, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
:return: 用户输入的文本
"""
item_spec, valid_func = _parse_args(locals())
Expand Down Expand Up @@ -285,7 +285,7 @@ def _set_options_selected(options, value):
return options


def select(label='', options=None, *, multiple=None, valid_func=None, name=None, value=None, required=None,
def select(label='', options=None, *, multiple=None, validate=None, name=None, value=None, required=None,
help_text=None, **other_html_attrs):
r"""下拉选择框。
Expand All @@ -308,7 +308,7 @@ def select(label='', options=None, *, multiple=None, valid_func=None, name=None,
最终选中项为 ``value`` 参数和 ``options`` 中设置的并集。
:type value: list or str
:param bool required: 是否至少选择一项
:param - label, valid_func, name, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
:param - label, validate, name, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
:return: 如果 ``multiple=True`` 时,返回用户选中的 ``options`` 中的值的列表;不设置 ``multiple`` 时,返回用户选中的 ``options`` 中的值
"""
assert options is not None, ValueError('Required `options` parameter in select()')
Expand All @@ -322,15 +322,15 @@ def select(label='', options=None, *, multiple=None, valid_func=None, name=None,
return single_input(item_spec, valid_func, lambda d: d)


def checkbox(label='', options=None, *, inline=None, valid_func=None, name=None, value=None, help_text=None,
def checkbox(label='', options=None, *, inline=None, validate=None, name=None, value=None, help_text=None,
**other_html_attrs):
r"""勾选选项。可以多选,也可以不选。
:param list options: 可选项列表。格式与 `select` 函数的 ``options`` 参数含义一致
:param bool inline: 是否将选项显示在一行上。默认每个选项单独占一行
:param list value: 勾选选项初始选中项。为选项值的列表。
你也可以通过设置 ``options`` 列表项中的 ``selected`` 字段来设置默认选中选项。
:param - label, valid_func, name, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
:param - label, validate, name, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
:return: 用户选中的 options 中的值的列表。当用户没有勾选任何选项时,返回空列表
"""
assert options is not None, ValueError('Required `options` parameter in checkbox()')
Expand All @@ -345,7 +345,7 @@ def checkbox(label='', options=None, *, inline=None, valid_func=None, name=None,
return single_input(item_spec, valid_func, lambda d: d)


def radio(label='', options=None, *, inline=None, valid_func=None, name=None, value=None, required=None,
def radio(label='', options=None, *, inline=None, validate=None, name=None, value=None, required=None,
help_text=None, **other_html_attrs):
r"""单选选项
Expand All @@ -354,7 +354,7 @@ def radio(label='', options=None, *, inline=None, valid_func=None, name=None, va
:param str value: 单选选项初始选中项的值。
你也可以通过设置 ``options`` 列表项中的 ``selected`` 字段来设置默认选中选项。
:param bool required: 是否至少选择一项
:param - label, valid_func, name, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
:param - label, validate, name, help_text, other_html_attrs: 与 `input` 输入函数的同名参数含义一致
:return: 用户选中的选项的值
"""
assert options is not None, ValueError('Required `options` parameter in radio()')
Expand Down Expand Up @@ -609,14 +609,14 @@ def read_file(data): # data: None or [{'filename':, 'dataurl', 'mime_type', 'la
return single_input(item_spec, valid_func, read_file)


def input_group(label='', inputs=None, valid_func=None, cancelable=False):
def input_group(label='', inputs=None, validate=None, cancelable=False):
r"""输入组。向页面上展示一组输入
:param str label: 输入组标签
:param list inputs: 输入项列表。列表的内容为对单项输入函数的调用,并在单项输入函数中传入 ``name`` 参数。
:param Callable valid_func: 输入组校验函数。
:param Callable validate: 输入组校验函数。
函数签名:``callback(data) -> (name, error_msg)``
``valid_func`` 接收整个表单的值为参数,当校验表单值有效时,返回 ``None`` ,当某项输入值无效时,返回出错输入项的 ``name`` 值和错误提示. 比如:
``validate`` 接收整个表单的值为参数,当校验表单值有效时,返回 ``None`` ,当某项输入值无效时,返回出错输入项的 ``name`` 值和错误提示. 比如:
.. exportable-codeblock::
:name: input_group-valid_func
Expand All @@ -631,7 +631,7 @@ def check_form(data):
data = input_group("Basic info",[
input('Input your name', name='name'),
input('Repeat your age', name='age', type=NUMBER)
], valid_func=check_form)
], validate=check_form)
put_text(data['name'], data['age'])
Expand Down Expand Up @@ -674,4 +674,4 @@ def check_form(data):

spec = dict(label=label, inputs=spec_inputs, cancelable=cancelable)
return input_control(spec, preprocess_funcs=preprocess_funcs, item_valid_funcs=item_valid_funcs,
form_valid_funcs=valid_func)
form_valid_funcs=validate)
32 changes: 16 additions & 16 deletions test/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ def check_age(p): # 检验函数校验通过时返回None,否则返回错误
if p > 60:
return 'Too old!!'

age = yield input("How old are you?", type=NUMBER, valid_func=check_age, help_text='age in [10, 60]')
age = yield input("How old are you?", type=NUMBER, validate=check_age, help_text='age in [10, 60]')
put_markdown(f'`{repr(age)}`')

# Codemirror
Expand All @@ -423,7 +423,7 @@ def check_age(p): # 检验函数校验通过时返回None,否则返回错误
# 输入组 cancelable
info = yield input_group("Cancelable", [
input('Input your name', name='name'),
input('Input your age', name='age', type=NUMBER, valid_func=check_age, help_text='age in [10, 60]')
input('Input your age', name='age', type=NUMBER, validate=check_age, help_text='age in [10, 60]')
], cancelable=True)
put_markdown(f'`{repr(info)}`')

Expand Down Expand Up @@ -457,18 +457,18 @@ def check_item(data):

info = yield input_group('Input group', [
input('Text', type=TEXT, datalist=['data-%s' % i for i in range(10)], name='text',
required=True, help_text='required=True', valid_func=check_item),
input('Number', type=NUMBER, value="42", name='number', valid_func=check_item),
input('Float', type=FLOAT, name='float', valid_func=check_item),
input('Password', type=PASSWORD, name='password', valid_func=check_item),
required=True, help_text='required=True', validate=check_item),
input('Number', type=NUMBER, value="42", name='number', validate=check_item),
input('Float', type=FLOAT, name='float', validate=check_item),
input('Password', type=PASSWORD, name='password', validate=check_item),

textarea('Textarea', rows=3, maxlength=20, name='textarea',
help_text='rows=3, maxlength=20', valid_func=check_item),
help_text='rows=3, maxlength=20', validate=check_item),

textarea('Code', name='code', code={
'lineNumbers': False,
'indentUnit': 2,
}, value='import something\n# Write your python code', valid_func=check_item),
}, value='import something\n# Write your python code', validate=check_item),

select('select-multiple', [
{'label': '标签0,selected', 'value': '0', 'selected': True},
Expand All @@ -478,7 +478,7 @@ def check_item(data):
('标签4,disabled', '4', False, True),
'标签5,selected',
], name='select-multiple', multiple=True, value=['标签5,selected'], required=True,
help_text='required至少选择一项', valid_func=check_item),
help_text='required至少选择一项', validate=check_item),

select('select', [
{'label': '标签0', 'value': '0', 'selected': False},
Expand All @@ -487,7 +487,7 @@ def check_item(data):
('标签3', '3'),
('标签4,disabled', '4', False, True),
'标签5,selected',
], name='select', value=['标签5,selected'], valid_func=check_item),
], name='select', value=['标签5,selected'], validate=check_item),

checkbox('checkbox-inline', [
{'label': '标签0,selected', 'value': '0', 'selected': False},
Expand All @@ -496,7 +496,7 @@ def check_item(data):
('标签3', '3'),
('标签4,disabled', '4', False, True),
'标签5,selected',
], inline=True, name='checkbox-inline', value=['标签5,selected', '标签0', '标签0,selected'], valid_func=check_item),
], inline=True, name='checkbox-inline', value=['标签5,selected', '标签0', '标签0,selected'], validate=check_item),

checkbox('checkbox', [
{'label': '标签0,selected', 'value': '0', 'selected': True},
Expand All @@ -505,7 +505,7 @@ def check_item(data):
('标签3', '3'),
('标签4,disabled', '4', False, True),
'标签5',
], name='checkbox', valid_func=check_item),
], name='checkbox', validate=check_item),

radio('radio-inline', [
{'label': '标签0', 'value': '0', 'selected': False},
Expand All @@ -514,7 +514,7 @@ def check_item(data):
('标签3', '3'),
('标签4,disabled', '4', False, True),
'标签5,selected',
], inline=True, name='radio-inline', value='标签5,selected', valid_func=check_item),
], inline=True, name='radio-inline', value='标签5,selected', validate=check_item),

radio('radio', [
{'label': '标签0', 'value': '0', 'selected': False},
Expand All @@ -523,7 +523,7 @@ def check_item(data):
('标签3', '3'),
('标签4,disabled', '4', False, True),
'标签5,selected',
], inline=False, name='radio', value='标签5,selected', valid_func=check_item),
], inline=False, name='radio', value='标签5,selected', validate=check_item),

file_upload('file_upload', name='file_upload', max_size='10m'),

Expand All @@ -536,9 +536,9 @@ def check_item(data):
{'label': '取消', 'type': 'cancel'},
], name='actions', help_text='actions'),

], valid_func=check_form)
], validate=check_form)

put_text('`valid_func()` log:')
put_text('`validate()` log:')
put_code(json.dumps(sorted(list(set(check_item_data))), indent=4, ensure_ascii=False), 'json')

put_text('Form result:')
Expand Down

0 comments on commit 4f5e672

Please sign in to comment.