user.py 1.32 KB
Newer Older
Weizhi Cui's avatar
Weizhi Cui committed
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version     : Python 3.11.4
# @Software    : Sublime Text 4
# @Author      : StudentCWZ
# @Email       : StudentCWZ@outlook.com
# @Date        : 2023/10/29 00:07
# @File        : user.py
# @Description :
"""

from pydantic import BaseModel, EmailStr, field_validator
from application.extensions.init_marshmallow import ma
from application.extensions.init_sqlalchemy import db
from application.models import User
from marshmallow import validates, ValidationError


class CreateUserItem(BaseModel):
    username: str
    password: str
    email: EmailStr

    @classmethod
    @field_validator("username")
    def name_must_contain_only_characters(cls, value):
        if not value.isalpha():
            raise ValueError("Username must contain only characters.")
        return value


class UserSchema(ma.SQLAlchemyAutoSchema):

    id = ma.Int(dump_only=True)
    username = ma.Str(required=True)
    password = ma.String(load_only=True, required=True)
    email = ma.Email(required=True)

    class Meta:
        model = User
        sqla_session = db.session
        load_instance = True
        exclude = ("_password",)

    @validates('username')
    def validate_username(self, username):
        if len(username) < 3:
            raise ValidationError('Username must be at least 3 characters.')