forked from hugapi/hug
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.py
More file actions
48 lines (36 loc) · 1.31 KB
/
validation.py
File metadata and controls
48 lines (36 loc) · 1.31 KB
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
import hug
from marshmallow import fields
from marshmallow.decorators import validates_schema
from marshmallow.schema import Schema
from marshmallow_sqlalchemy import ModelSchema
from demo.context import SqlalchemyContext
from demo.models import TestUser, TestModel
@hug.type(extend=hug.types.text, chain=True, accept_context=True)
def unique_username(value, context: SqlalchemyContext):
if context.db.query(
context.db.query(TestUser).filter(
TestUser.username == value
).exists()
).scalar():
raise ValueError('User with a username {0} already exists.'.format(value))
return value
class CreateUserSchema(Schema):
username = fields.String()
password = fields.String()
@validates_schema
def check_unique_username(self, data):
if self.context.db.query(
self.context.db.query(TestUser).filter(
TestUser.username == data['username']
).exists()
).scalar():
raise ValueError('User with a username {0} already exists.'.format(data['username']))
class DumpUserSchema(ModelSchema):
@property
def session(self):
return self.context.db
class Meta:
model = TestModel
fields = ('name',)
class DumpSchema(Schema):
users = fields.Nested(DumpUserSchema, many=True)