我有一个 Flask 应用程序,我使用棉花糖模式来验证我的请求,如下所示:
class HyperParameterSchema(Schema):
name = fields.Str(required=True)
data_type = fields.Str(required=True)
default_value = fields.Str(required=True)
class LearnerRequestSchema(Schema):
files = fields.Raw(type="file")
name = fields.Str(required=True)
description = fields.Str(required=True)
supervision_scope = fields.Enum(SupervisionScope, by_value=True, required=True)
task_type = fields.Enum(TaskType, by_value=True, required=True)
tool = fields.Enum(Tool, by_value=True, required=True)
learner_family_id = fields.Int(required=True)
hyperparams = fields.List(
fields.Nested(HyperParameterSchema, many=True),
)
当我执行如下请求时:
response = requests.post(
url="http://localhost:8080/api/learners",
data={
"name": "some_name",
"description": "some_description",
"supervision_scope": "supervised",
"task_type": "classification",
"tool": "scikit-learn",
"learner_family_id": 1,
"hyperparams": json.dumps(
[
{"name": "alpha", "data_type": "float", "default_value": "0.1"},
{"name": "l1_ratio", "data_type": "float", "default_value": "0.1"},
]
),
},
files={
"file": open("path_to_file", "rb")
},
headers=headers,
)
我不断收到响应 b'{"errors":{"form":{"hyperparams":{"0":["Invalid type."]}}}} '.
验证不应该按照其实现的方式进行吗?有人可以帮我找出我可能做错了什么吗?谢谢!
目前,我正在使用 fields.Raw 类来处理上述相关问题:
class LearnerRequestSchema(Schema):
files = fields.Raw(type="file")
name = fields.Str(required=True)
description = fields.Str(required=True)
supervision_scope = fields.Enum(SupervisionScope, by_value=True, required=True)
task_type = fields.Enum(TaskType, by_value=True, required=True)
tool = fields.Enum(Tool, by_value=True, required=True)
learner_family_id = fields.Int(required=True)
hyperparams = fields.Raw()
问题是我必须手动反序列化超参数字段才能检查所需的字段是否存在,而在前一种方法中我将立即进行验证。
Marshmallow 需要
hyperparams
的列表列表,因为您已在嵌套字段中设置 many=True
,并将其包装在列表字段中。
您可以删除列表或
many=True
,因为它们都在做同样的事情。以下任何一项都应该适合您想要实现的目标。我更喜欢fields.Nested(Schema, many=True)
我自己。
class LearnerRequestSchema(Schema):
...
hyperparams = fields.List(
fields.Nested(HyperParameterSchema),
)
class LearnerRequestSchema(Schema):
...
hyperparams = fields.Nested(HyperParameterSchema, many=True)