File: validation.py

package info (click to toggle)
python-hug 2.6.0-2.4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,072 kB
  • sloc: python: 8,938; sh: 99; makefile: 17
file content (43 lines) | stat: -rw-r--r-- 1,280 bytes parent folder | download
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
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)