29 lines
1.3 KiB
Python
29 lines
1.3 KiB
Python
from extensions import db # 从扩展模块导入初始化好的 SQLAlchemy 数据库实例
|
||
|
||
|
||
# 定义 User 类,继承自 db.Model,使其成为一个数据库模型类(对应数据库的一张表)
|
||
class User(db.Model):
|
||
# 【表配置】显式指定在数据库中生成的表名为 "users"
|
||
__tablename__ = "users"
|
||
|
||
# 【字段定义】
|
||
# id:字段名;db.Integer:整数类型;primary_key=True:设为主键(通常会自动自增)
|
||
id = db.Column(db.Integer, primary_key=True)
|
||
|
||
# username:用户名;db.String(64):最大长度64的字符串
|
||
# unique=True:值必须唯一(不可重复);nullable=False:不允许为空(必填项)
|
||
username = db.Column(db.String(64), unique=True, nullable=False)
|
||
|
||
# password:密码;db.String(128):最大长度128(通常存加密后的哈希串)
|
||
# nullable=False:不允许为空
|
||
password = db.Column(db.String(128), nullable=False)
|
||
|
||
# 【实例方法:序列化】
|
||
# 将数据库对象转换为 Python 字典,方便在 Web 开发中返回 JSON 数据给前端
|
||
def to_dict(self):
|
||
return {
|
||
"id": self.id,
|
||
"username": self.username
|
||
# 注意:出于安全考虑,通常不会在 to_dict 中返回 password 字段
|
||
}
|