|
| 1 | +""" |
| 2 | +1.pep249: https://peps.python.org/pep-0249/ |
| 3 | +2.flask-sqlalchemy: https://flask-sqlalchemy.palletsprojects.com/en/2.x/ |
| 4 | +""" |
| 5 | +from datetime import datetime |
| 6 | + |
| 7 | +from werkzeug.security import generate_password_hash, check_password_hash |
| 8 | + |
| 9 | +from python_talk.extensions import db |
| 10 | + |
| 11 | + |
| 12 | +class Base(db.Model): |
| 13 | + __abstract__ = True |
| 14 | + |
| 15 | + created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) |
| 16 | + update_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow) |
| 17 | + |
| 18 | + def __repr__(self): |
| 19 | + return f'<{self.__class__.__name__!r} {self.__dict__!r}>' |
| 20 | + |
| 21 | + def save(self): |
| 22 | + db.session.add(self) |
| 23 | + db.session.commit() |
| 24 | + return self |
| 25 | + |
| 26 | + |
| 27 | +class User(Base): |
| 28 | + id = db.Column(db.Integer, primary_key=True) |
| 29 | + username = db.Column(db.String(100), nullable=False, unique=True) |
| 30 | + email = db.Column(db.String(100), nullable=False, unique=True) |
| 31 | + __password = db.Column('password', db.String(255), nullable=False) |
| 32 | + avatar = db.Column(db.String(512)) |
| 33 | + |
| 34 | + def __init__(self, username, email, password, avatar=None): |
| 35 | + self.username = username |
| 36 | + self.email = email |
| 37 | + self.password = password |
| 38 | + self.avatar = avatar |
| 39 | + |
| 40 | + @property |
| 41 | + def password(self): |
| 42 | + raise AttributeError('password field is not allowed to access') |
| 43 | + |
| 44 | + @password.setter |
| 45 | + def password(self, value): |
| 46 | + self.__password = generate_password_hash(value) |
| 47 | + |
| 48 | + def check_password(self, value): |
| 49 | + return check_password_hash(self.__password, value) |
0 commit comments