python - 是否可以在棉花糖中定义具有互斥字段的嵌套模式?

标签 python python-3.x flask flask-restful marshmallow

我正在使用 marshmallow 来验证我在 flask restful api 中接收到的 json 数据。然而,在post 请求中有一个互斥字段
例如 : {"predict": {"id": "5hgy667y4h7f"}}{"predict": {"text": "This is a sample sentence"}}< br/> 但是 NOT idtext 应该一起发送。此外,根据接收到的天气 idtext 调用不同的方法。

问)我如何在 marshmallow 中构建一个允许我验证上述内容的模式?

我对任一字段的示例代码如下 -

from flask import Flask, request
from flask_restful import Resource, Api, abort
from marshmallow import Schema, fields, ValidationError
app = Flask(__name__)
api = Api(app)

class Mutex1(Schema):
    text = fields.Str(required=True)
    class Meta:
        strict = True

class Mutex2(Schema):
    id_ = fields.Str(required=True)
    class Meta:
        strict = True

class MySchema(Schema):
    predict = fields.Nested(Mutex1)
    class Meta:
        strict = True

class Test(Resource):
    def post(self):
        input_req = request.get_json(force=True)
        try:
            result = MySchema().load(input_req)
        except ValidationError:
            return {'message': 'Validation Error'}, 500
        else:
            return {'message': 'Successful validation'}, 200

api.add_resource(Test, '/test')
app.run(host='0.0.0.0', port=5000, debug=True)

此代码仅接受 text 和带有 id_text,但它仅拒绝 id_。知道如何让它接受 id_ 并在一起传递时拒绝 textid_ 吗?

最佳答案

创建一个包含textid_Mutex 模式并添加一个schema-level validation如果两者都提供则失败。

class Mutex(Schema):

    @validates_schema
    def validate_numbers(self, data):
        if (
               ('text' in data and 'id_' in data) or
               ('text' not in data and 'id_' not in data)
           ):
            raise ValidationError('Only one of text and _id is allowed')

    text = fields.Str()
    id_ = fields.Str()
    class Meta:
        strict = True

旁注:

  • 输入验证错误不应返回 500(服务器错误),而是 422。
  • 我不熟悉 flask-restful,但看起来你可以使用 webargs 来节省一些样板文件。解析资源输入。

关于python - 是否可以在棉花糖中定义具有互斥字段的嵌套模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55165795/

相关文章:

python - 有没有办法将 Python/Tkinter 连接到已经运行的 Tcl/Tk 应用程序?

python - Pandas:数据帧错误 - 传递了 2 列,传递的数据有 3 列

ember.js - 您可以使用两个HTML模板,例如Handlebars和Jinja

python - 在 CSV 文件中搜索特定字符串时遇到问题

python - 404 尝试链接到另一个页面 Flask 时出错

python - Bcrypt salt 将字节对象视为字符串并且不会散列密码

list - 将列表元素与其索引相关联的 Pythonic 方式

python - 如何在不显示 Django 表单中的字段的情况下设置表单字段默认值?

python - 为什么字符串变量在更改时不更新

python-3.x - Python 3 http.server - 一个奇怪的IP地址试图连接我的服务器