在校验请求参数的时候,type 参数类型可以设置为正则匹配,邮箱匹配,url匹配等在inputs模块有补充。
flask_restful.inputs 常用的一些数据校验
写一个注册视图,对请求入参校验
class RegisterView(Resource):
def post(self):
# 创建解析器对象
parser = reqparse.RequestParser()
# 需要验证的参数
parser.add_argument('username', type=str, required=True, trim=True, help='用户名不合法' )
parser.add_argument('password', type=str, required=True, help='密码不合法')
parser.add_argument('age', type=int, help='年龄不合法')
parser.add_argument('sex', type=str, choices=['男', '女'], help='性别不合法')
parser.add_argument('birthday', type=inputs.date, help='生日类型不合法')
parser.add_argument('phone', type=inputs.regex(r'1[3578]\d{9}'), help='手机号不合法')
parser.add_argument('url', type=inputs.url, help='url不合法')
args = parser.parse_args()
print(f'请求入参:{args}')
return {"code": 0}
请求参数示例
{
"username": "test",
"password" : "12345",
"age": 22,
"sex": "男",
"birthday": "2021-01-09",
"phone": "134444322222",
"url": "https://www.cnblogs.com/yoyoketang/"
}
add_argument方法可以指定这个字段的名字,这个字段的数据类型等,验证错误提示信息等。
自定义type 请求入参类型,参考这篇https://www.cnblogs.com/yoyoketang/p/16647988.html
2022年第 12期《python接口web自动化+测试开发》课程,9月17号开学!
本期上课时间:2022年9月17号 - 2022年12月17号,周六周日上午9:00-11:00