你如何将默认值传递给 flask-restplus 中的有效负载?

How do you pass default values to payload in flask-restplus?

我正在设置一个 restplus API,并希望在查询不包含这些值时传递一些默认字段。我如何使用 api 模型传递这些,最好不使用 requestParser?

就目前而言,负载不会受到设置默认值的影响,因此没有必要。我已经尝试使参数成为必需的,但这没有用,因为我希望能够仅传递部分预期有效负载。

from flask import Flask, request
from flask_restplus import Api, Resource, fields

app = Flask(__name__)
api = Api(app=app)
model = api.model("simple_model", {'some_bool': fields.Boolean(required=False, default=False),
                                   'some_int': fields.Integer(required=False, default=99)})


@api.route('/foo')
class SomeClass(Resource):

    @api.expect(model)
    def post(self):
        return request.json


if __name__ == '__main__':
    app.run(host='localhost', port=8000, threaded=False, debug=True)

使用代码进行测试

import requests

query = {"some_bool": True, "some_int": 20}
res = requests.post("http://localhost:8000/foo", json=query)
print(res.json())

query = {"some_bool": True}
res = requests.post("http://localhost:8000/foo", json=query)
print(res.json())

query = {"some_int": 20}
res = requests.post("http://localhost:8000/foo", json=query)
print(res.json())

res = requests.post("http://localhost:8000/foo")
print(res.json())

这给出了输出

{'some_bool': True, 'some_int': 20}

{'some_bool': True}

{'some_int': 20}
None

期望值,期望输出为

{'some_bool': True, 'some_int': 20}

{'some_bool': True, 'some_int': 99}

{'some_bool': False, 'some_int': 20}

{'some_bool': False, 'some_int': 99}

感谢所有帮助。

编辑:

在@IMCoins 回答后,我最终编写了一个函数,使我能够像这样访问函数内的项目

def get_content(api_model):
   @marshal_with(api_model)
   def get_request():
      return request.json
   return get_request()

然后访问里面的内容为

content = get_content(model)

据我了解,如果您想确保在入口点拥有所需的所有密钥,则需要使用 RequestParser()api.expect() 装饰器用于记录 swagger。

但是,如果您想确保您的请求始终 returns 一个基本模板(类似于此处的模型),您可以将您创建的模型用于装饰器 api.marshal_with()

例如,在此处的示例中,只需将 expect 替换为 marshal_with,它将在响应中包含缺失值。

我认为没有请求Parser,是不可能得到你想要的。这个默认关键字实际上并不是答案。因为如果您尝试使用日志进行调试,它只会接收您作为查询传递的内容。但是 api 没有在丢失的情况下添加默认参数, Required 参数在那里也不起作用。所以我想按照@IMCoins 的描述使用它?

jsonschema 实际上有一个解决方案...但没有将它包含在主库中:

https://python-jsonschema.readthedocs.io/en/stable/faq/#why-doesn-t-my-schema-s-default-property-set-the-default-on-my-instance

schema = {'some_bool' {'type': 'bool', 'default': 'false'}, 'some_int': {'type': 'number', 'default': 99}}

def post()
   data = request.json
   DefaultValidatingDraft7Validator(schema).validate(data)
   return data

应该导致

res = requests.post("http://localhost:8000/foo")
print(res.json())
{'some_bool': False, 'some_int': 99}