根据数据覆盖字段模式-棉花糖

时间:2019-04-12 16:08:35

标签: python validation flask-restful marshmallow

我刚开始使用棉花糖,所以如果有解决问题的更优雅的方法,请告诉我。 字段将根据用户类型(学生/工作人员)而变化

{
   "type": "student",   
   "name": "Student 1",
   "class": "V Std",
   "section": "A Class"
}

如果类型为Staff,我们需要验证designationexperience跳过classsection

{
   "type": "staff",   
   "name": "Staff 1",
   "designation": "Professor",
   "experience": "2 Year"
}

我有以下简单的模型和架​​构。

class AddUser(Resource):
   def post(self):
      content = request.get_json(silent=True)
      try:
         data = UserSchema().load(content)       
         print(data)

      except ValidationError as err:
         return err.messages, 400

class UserSchema(Schema):
   type = fields.Str(required=True,validate=OneOf(['student', 'staff'], error='Invalid User Type'), error_messages={'required': 'User type required'})
   name = fields.Str(required=True)
   class = fields.Str()
   section = fields.Str()
   designation = fields.Str()
   experience = fields.Str()

   @post_load
   # @pre_load
   # @validates_schema
   def unwrap_envelope(self, data):   
     student = {
       class: fields.Str(required=True),
       section: fields.Str(required=True)
     }

      staff = {
       designation: fields.Str(required=True),
       experience: fields.Str(required=True)
     }

     # Fields are getting updated but it is **not raising the error**

     if data['type'] == 'student':
       self.declared_fields.update(student)
     elseif data['type'] == 'staff':
       self.declared_fields.update(staff)

     return data

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找的是多态性。

要实现这一目标并非易事,而且棉花糖还没有简便的实现方法。您可以检查marshmallow-oneofschemamarshmallow-polyfield。这两个第三方库就是为此目的而设计的。它们都有自己的优缺点,因此它们都不包含在棉花糖芯中。