Flask 学习-82.Flask-RESTX使用reqparse 解析器校验枚举类型choices 参数
前言
reqparse.RequestParser() 解析器可以校验枚举类型,在add_argument中使用choices参数
choices 设置参数可选值
比如性别设置可选项:男、女
def post(self):
# 校验入参
parser = reqparse.RequestParser()
parser.add_argument('username', required=True, type=str, nullable=False, help='username is required')
parser.add_argument('password', required=True, type=str, nullable=False, help='password is required')
parser.add_argument('sex', choices=["男", "女"], type=str, help='sex invalid')
args = parser.parse_args()
print(f'请求入参:{args}')
请求示例,sex不是可选项的时候会报400
POST http://127.0.0.1:5000/api/v1/register HTTP/1.1
User-Agent: Fiddler
Host: 127.0.0.1:5000
Content-Type: application/json
Content-Length: 73
{
"username": "test",
"password" : "111111",
"sex": "x"
}
HTTP/1.0 400 BAD REQUEST
Content-Type: application/json
Content-Length: 152
Server: Werkzeug/2.0.1 Python/3.8.5
Date: Sun, 04 Sep 2022 12:26:41 GMT
{
"errors": {
"sex": "sex invalid The value 'x' is not a valid choice for 'sex'."
},
"message": "Input payload validation failed"
}