· 6 years ago · May 15, 2019, 07:38 PM
1import marshmallow
2import json
3from marshmallow import validates_schema, ValidationError
4
5class UserPostListSchema(marshmallow.Schema):
6 """
7 Serialization schema for user post list
8 """
9 id = marshmallow.fields.Int()
10 email = marshmallow.fields.Str(default=False)
11 password = marshmallow.fields.Str(default=False)
12 oauth_provider = marshmallow.fields.Str(default=False)
13 oauth_token = marshmallow.fields.Str(default=False)
14
15 # This is giving me trouble where it'll throw a key error instead of just checking if one of these pairs exist.
16 @validates_schema
17 def validate_email(self, data):
18 if not (data['email'] and data['password']) or not (data['oauth_provider'] and data['oauth_token']):
19 raise ValidationError('Validation requires either an email and password or provider and oauth token')
20
21request_data_email = dict(email="test@gmail.com", password="test")
22request_data_oauth = dict(oauth_provider="test@gmail.com", oauth_token="test")
23
24json_data = json.dumps(request_data_email)
25user_schema = UserPostListSchema()
26data, errors = user_schema.loads(json_data=json_data)
27print(data)
28print(errors)