我在node项目中具有以下Joi模式验证,我计划使用棉花糖库将其转换为python。
Joi模式:
aws_access_key: Joi.string().label('AWS ACCESS KEY').required().token().min(20),
aws_secret_key: Joi.string().label('AWS SECRET KEY').required().base64().min(40),
encryption: Joi.string().label('AWS S3 server-side encryption').valid('SSE_S3', 'SSE_KMS', 'CSE_KMS').optional(),
kmsKey: Joi.string().label('AWS S3 server-side encryption KMS key').when('encryption', { is: Joi.valid('SSE_KMS', 'CSE_KMS'), then: Joi.string().required() })
到目前为止,这是我到目前为止在python中使用棉花糖所做的事情
from marshmallow import Schema, fields
from marshmallow.validate import OneOf, Length
class AWSSchema(Schema):
aws_access_key = fields.String("title", required=True, validate=Length(min=20))
aws_secret_key = fields.String(required=True, validate=Length(min=40))
encryption = fields.String(required=False, validate=OneOf(['SSE_S3', 'SSE_KMS', 'CSE_KMS']))
kmskey = fields.String(validate=lambda obj: fields.String(required=True) if obj['encryption'] in ('SSE_KMS', 'CSE_KMS') else fields.String(required=False))
demo = {
"aws_access_key": "AKXXXXXXXXXXXXXXXXXXX",
"aws_secret_key": "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY",
"encryption_type": "SSE_KMS"
}
schema = AWSSchema()
print(schema.dump(demo))
如果encryption_type值设置为SSE_KMS或CSE_KMS,则我需要kmskey字段应为必填字段。但是验证未按预期进行。任何帮助表示赞赏吗?
答案 0 :(得分:0)
棉花糖有一些可以覆盖的方法,可以在转储或加载过程的各个点进行顶级验证。 pre_dump
的文档可以在这里找到。还要检出pre_load
和post_dump
。
https://marshmallow.readthedocs.io/en/stable/api_reference.html#marshmallow.decorators.pre_dump