简体   繁体   English

如何为不同的请求添加不同的flask-restful reqparse要求

[英]How to add different flask-restful reqparse requirements for different requests

I'm creating a login endpoint like this for an example:我正在创建一个这样的登录端点作为示例:

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 {
            .
            .
            .

The problem is that both arguments now - email and password alike - are mandatory to give.问题是现在这两个参数 - 电子邮件和密码一样 - 都是强制性的。 But what if I want to create another endpoint class which would only need one of them as a filled field?但是,如果我想创建另一个只需要其中一个作为填充字段的端点类呢? Clearly removing the required = True parameter would solve this, but that would break class UserLogin 's logic for validation.显然删除required = True参数可以解决这个问题,但这会破坏class UserLogin的验证逻辑。

Is there any ready made resource or pattern to do that?有没有现成的资源或模式来做到这一点?

Parser Inheritance解析器继承

Often you will make a different parser for each resource you write.通常,您会为您编写的每个资源制作不同的解析器。 The problem with this is if parsers have arguments in common.问题在于解析器是否有共同的参数。 Instead of rewriting arguments you can write a parent parser containing all the shared arguments and then extend the parser with copy() .您可以编写一个包含所有共享参数的父解析器,然后使用copy()扩展解析器,而不是重写参数。 You can also overwrite any argument in the parent with replace_argument() , or remove it completely with remove_argument() .您还可以使用replace_argument()覆盖父级中的任何参数,或使用remove_argument()将其完全删除。 For example:例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM