user.py 2.06 KB
Newer Older
Weizhi Cui's avatar
Weizhi Cui committed
1 2 3 4 5 6 7 8 9 10 11 12
#!/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/28 22:12
# @File        : user.py
# @Description :
"""

崔为之's avatar
崔为之 committed
13 14
from datetime import datetime
from sqlalchemy import text
Weizhi Cui's avatar
Weizhi Cui committed
15 16 17 18 19 20 21 22
from sqlalchemy.ext.hybrid import hybrid_property

from application.extensions.init_bcrypt import bcrypt
from application.extensions.init_sqlalchemy import db


class User(db.Model):
    """Basic user model"""
崔为之's avatar
崔为之 committed
23
    __tablename__ = 'users'
Weizhi Cui's avatar
Weizhi Cui committed
24 25 26 27 28 29

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(80), unique=True, nullable=False)
    _password = db.Column("password", db.String(255), nullable=False)
    active = db.Column(db.Boolean, default=True)
崔为之's avatar
崔为之 committed
30
    created_at = db.Column(db.DateTime, nullable=False)
Weizhi Cui's avatar
Weizhi Cui committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def password(self, password: str):
        self._password = bcrypt.generate_password_hash(password).decode('utf-8')

    def check_password(self, password: str):
        # 判断传过来的密码是否与数据库存的密码一致
        return bcrypt.check_password_hash(self._password, password)

    def to_dict(self) -> dict:
        """object to dict"""
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
        }

    def __repr__(self) -> str:
        return f'<User {self.username}>'
崔为之's avatar
崔为之 committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67

    def save(self):
        partition_date = self.created_at.strftime('%Y_%m')
        partition_name = f'users_{partition_date}'

        with db.session.begin_nested():
            db.session.execute(text(f"""
            CREATE TABLE IF NOT EXISTS {partition_name} PARTITION OF users
            FOR VALUES FROM ('{self.created_at.strftime('%Y-%m-01')}') TO 
            ('{self.created_at.strftime('%Y-%m-01')}'::date + interval '1 month');
            """))
            db.session.add(self)
        db.session.commit()