如何为不同的请求添加不同的flask-restful reqparse要求
How to add different flask-restful reqparse requirements for different requests
我正在创建一个这样的登录端点作为示例:
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('email', help = 'This field cannot be blank', required = True)
parser.add_argument('password', help = 'This field cannot be blank', required = True)
class UserLogin(Resource):
def post(self):
data = parser.parse_args()
current_user = User.find_by_email(data['email'])
if not current_user:
return {
.
.
.
问题是现在这两个参数 - 电子邮件和密码 - 都必须提供。但是如果我想创建另一个端点 class 只需要其中一个作为填充字段怎么办?显然删除 required = True
参数可以解决这个问题,但这会破坏 class UserLogin
的验证逻辑。
是否有任何现成的资源或模式可以做到这一点?
解析器继承
通常您会为您编写的每个资源制作不同的解析器。问题是解析器是否有共同的参数。您可以编写包含所有共享参数的父解析器,然后使用 copy() 扩展解析器,而不是重写参数。您还可以使用 replace_argument() 覆盖父级中的任何参数,或者使用 remove_argument() 完全删除它.例如:
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('foo', type=int)
parser_copy = parser.copy()
parser_copy.add_argument('bar', type=int)
# parser_copy has both 'foo' and 'bar'
parser_copy.replace_argument('foo', required=True, location='json')
# 'foo' is now a required str located in json, not an int as defined
# by original parser
parser_copy.remove_argument('foo')
# parser_copy no longer has 'foo' argument
我正在创建一个这样的登录端点作为示例:
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('email', help = 'This field cannot be blank', required = True)
parser.add_argument('password', help = 'This field cannot be blank', required = True)
class UserLogin(Resource):
def post(self):
data = parser.parse_args()
current_user = User.find_by_email(data['email'])
if not current_user:
return {
.
.
.
问题是现在这两个参数 - 电子邮件和密码 - 都必须提供。但是如果我想创建另一个端点 class 只需要其中一个作为填充字段怎么办?显然删除 required = True
参数可以解决这个问题,但这会破坏 class UserLogin
的验证逻辑。
是否有任何现成的资源或模式可以做到这一点?
解析器继承
通常您会为您编写的每个资源制作不同的解析器。问题是解析器是否有共同的参数。您可以编写包含所有共享参数的父解析器,然后使用 copy() 扩展解析器,而不是重写参数。您还可以使用 replace_argument() 覆盖父级中的任何参数,或者使用 remove_argument() 完全删除它.例如:
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('foo', type=int)
parser_copy = parser.copy()
parser_copy.add_argument('bar', type=int)
# parser_copy has both 'foo' and 'bar'
parser_copy.replace_argument('foo', required=True, location='json')
# 'foo' is now a required str located in json, not an int as defined
# by original parser
parser_copy.remove_argument('foo')
# parser_copy no longer has 'foo' argument