使用 flask_restful 的 reqparse,您是否能够忽略未包含在参数或 json 中的值?

Using flask_restful's reqparse, are you able to ignore values not included in params or json?

假设您有一个针对 API 的请求,并且您正在使用 flask_restful.reqparse 来处理请求的参数和正文。

POST {{url}}/users
Content-Type: application/json

{
    "firstName": "First",
    "lastName": "Last",
    "age": 25
}
parser = reqparse.RequestParser()
parser.add_argument("firstName", type=str)
parser.add_argument("lastName", type=str)
parser.add_argument("age", type=int)
parser.add_argument("valueInQuestion", type=str)

是否可以在调用 .parse_args() 时不包含请求中未找到的值?例如,在上面的解析器中我们有 valueInQuestion 但请求正文不包含此字段。

我从解析器返回的是:{'firstName': 'First', 'lastName': 'Last', 'age': 25, 'valueInQuestion': None}.

我想从解析器返回的是:{'firstName': 'First', 'lastName': 'Last', 'age': 25} 因为 valueInQuestion 不包括在内。

编辑:我知道我可以从字典中过滤 None 值。我不想这样做,因为如果用户使用 {...valueInQuestion: null} 发出 POST 请求,我想保留该值,而不是将其过滤掉。

您也可以只从字典中过滤掉值为 None 的项目,以防万一如果这适合您

res = {k:v for k,v in your_dict.items() if v is not None}

Argument 构造函数有参数 store_missing - 默认设置为 True。通过将这个参数设置为 False 我们只得到请求中传递的值,其他解析器参数被跳过,所以我们得到没有 None 值的字典。如果有人正在寻找解决方案,此参数可能会有所帮助。

来源: flask-restful/reqparse.py

编辑:

reqparse docs say "The whole request parser part of Flask-RESTful is slated for removal and will be replaced by documentation on how to integrate with other packages that do the input/output stuff better (such as marshmallow)。这意味着它将一直维护到 2.0,但认为它已被弃用。别担心,如果您现在有使用它的代码并希望继续这样做,它不会很快消失。"