python - 是否可以在棉花糖中定义具有互斥字段的嵌套模式?
问题描述
我正在使用棉花糖来验证我在烧瓶 restful api 中收到的 json 数据。然而,在post请求中有一个互斥字段。
例如 :
{"predict": {"id": "5hgy667y4h7f"}}
or {"predict": {"text": "This is a sample sentence"}}
But NOT both id
andtext
应该一起发送。此外,根据天气调用id
或text
接收不同的方法。
问)我如何在棉花糖中构建一个允许我验证上述内容的模式?
我为任一字段提供的示例代码如下 -
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
和text
with id_
,但仅拒绝id_
。知道如何让它接受id_
和拒绝两者text
以及id_
何时一起通过吗?
解决方案
使用两者创建一个Mutex
模式,text
并id_
添加模式级验证以失败,如果两者都提供。
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 - 使用 Boto 自动上传到 AWS S3 存储桶 Yields Expired Token Error
- python - 使用 Opencv 进行人脸检测
- firebase - 具有多个字段的 Firestore 分布式计数器
- node.js - 向 mongoDB 插入数据时显示 db 未定义
- python - 使硒无法检测的措施
- sql - Visual Studio SQL 返回重复值
- spring - java_options 中的第二个弹簧配置文件
- javascript - 为什么在 JavaScript 对象的 getter 和 setter 上使用 delete?
- javascript - 原生 JS 使用每个父类上的计数器重置添加类
- swift - 查找并更新具有关联值的 Swift 枚举数组