-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathflask-marshmallow.py
62 lines (49 loc) · 1.96 KB
/
flask-marshmallow.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from flask import Flask, request
from marshmallow import Schema, fields, ValidationError, pprint, validates_schema
app = Flask(__name__)
class NumberSchema(Schema):
field_a = fields.Integer(required=True, error_messages={"required": "Please enter name."})
field_b = fields.Integer()
@validates_schema(skip_on_field_errors=True)
def conditional_validation(self, data, **kwargs):
if data["field_a"] != 'mia':
raise ValidationError("field_a must be greater than field_b")
class UserDTO(Schema):
name = fields.String(required=True, error_messages={"required": "Please enter name."})
email = fields.Email(required=True, error_messages={"required": "Please enter email.", "invalid": "Invalid email address."})
age = fields.Float()
@validates_schema
def conditional_validation(self, data, **kwargs):
if data["name"] != 'mia':
raise ValidationError("field_a must be greater than field_b")
@app.route("/")
def index():
return "index"
@app.route("/validation", methods=['POST', 'GET'])
def validation():
schema = NumberSchema()
try:
schema.load({"field_a": 1, "field_b": 2})
schema.validate({"field_a": 1, "field_b": 2})
except ValidationError as err:
print("error")
return "validation"
@app.route("/user/create", methods=['POST'])
def create_user():
try:
user = UserDTO()
try:
user.load({"field_a": 1, "field_b": 2})
except ValidationError as err:
print("error")
return {"data": {"status": "success", "message": "Validation Success"}}
except ValidationError as err:
errors = {}
if err and err.messages:
for message in err.messages:
error_text = ""
for text in err.messages[message]:
error_text += text
errors[message] = error_text
pprint(err.messages)
return {"data": {"status": "error", "errors": errors}}