#!/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 : """ from datetime import datetime from sqlalchemy import text 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""" __tablename__ = 'users' 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) created_at = db.Column(db.DateTime, nullable=False) @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'' 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()