Python烧瓶响应验证



我使用python钢筋来验证request_body_schema,它运行良好。我们可以验证输入的body参数。很酷,我们不想实现任何手动输入验证,比如添加if语句。

同样,我无法验证响应参数。

但是flask_rebar提到我们可以实现链接

Opting In to Response Validation
There are two ways to opt-in to response validation:
Globally, via validate_on_dump attribute of your Rebar instance. Using this method, it is easy to turn on validation for things like test cases, while reaping performance gains by leaving it off in your production endpoints (assuming your API contract testing is sufficient to guarantee that your API can’t return invalid data).
At schema level, via flask_rebar.validation.RequireOnDumpMixin (including if you use our legacy pre-canned ResponseSchema as the base class for your schemas). Any schema that includes that mixin is automatically opted in to response validation, regardless of global setting. Note that in Flask-Rebar 2, that mixin serves only as a “marker” to trigger validation; we plan to augment/replace this with ability to use SchemaOpts as a more logical way of accomplishing the same thing in the near future (https://github.com/plangrid/flask-rebar/issues/252).

但我没有得到任何例子,有人能帮我举的例子吗

我的代码:

from marshmallow import fields, Schema
from flask import Flask
from flask_rebar import Rebar, RequestSchema, get_validated_body
class CreateAccountSchema(RequestSchema):
email = fields.String(required=True)
country = fields.String(required=True)
default_currency = fields.String(required=True)

class AccountSchema(Schema):
id = fields.String()
email = fields.String()
country = fields.String()
default_currency = fields.String(required=True) # if this is not passed raise error

rebar = Rebar()
registry = rebar.create_handler_registry(prefix="/v1")
@registry.handles(
rule='/accounts',
method='POST',
marshal_schema={201: AccountSchema()},
request_body_schema=CreateAccountSchema(),)
def get_todos():
"""
This docstring will be rendered as the operation's description in
the auto-generated OpenAPI specification.
"""
body = get_validated_body()
body = rebar.validated_body
data = {"id": "myname", "email": "myemail", "country": "any"}
return data, 201
@registry.handles(
rule='/values',
method='GET',
marshal_schema=None,)
def get_values():
"""
This docstring will be rendered as the operation's description in
the auto-generated OpenAPI specification.
"""
data = {"id": "myname", "email": "myemail", "country": "any"}
return 'Hello, Poorvika'
def create_app(name) -> Flask:
app = Flask(name)
rebar.init_app(app)
return app
if __name__ == '__main__':
create_app(__name__).run()

要使示例在Flask Rebar 2.0中工作,必须将@registry.handle装饰器中的marshal_schema参数替换为response_body_schemamarshal_schema是旧的不推荐使用的名称,已在Rebar 2.0中删除。钢筋1.7中引入了新名称response_body_schema

response_body_schema是一个将用于封送函数返回值的Marshmallow模式。棉花糖。将对返回值调用Schema.dump。response_body_schema也可以是一个将状态代码映射到Marshmallow模式的字典-请参阅编组。注:在Flask Rebar 1.0-1.7.0中,这被称为marshal_schema。它正在被重命名,这两个名称将一直运行到2.0版本。–基础知识-烧瓶钢筋文档

https://flask-restplus.readthedocs.io/en/stable/marshalling.html

`@api.marshal_with`

用户响应封送