from sqlalchemy import Integer
from server import db
"""
User表的实体类,与DB字段一致
"""classUserEntity(db.Model):# 表名, 需要重新命名,默认按类名来创建表名
__tablename__ ="user"# 唯一主键IDid= db.Column(Integer,primary_key=True)# 用户名,唯一,不可为空
username = db.Column(db.String(64), nullable=False, unique=True)# 密码,不为空
password = db.Column(db.String(128), nullable=False)defuser_entity_dict(self):return{"id": self.id,"username": self.username,"password": self.password}
在do的_init_.py文件写入create_all()方法来初始化创建表
from server import db
from do.user_entity import UserEntity # 倒入要执行的实体类包"""
数据库表创建,运行文件创建
注意:创建一次后,就可以注释掉,避免之后每次启动项目都创建
"""if __name__ =="__main__":
db.create_all()
执行创建表
/usr/local/bin/python3.8/Applications/Python/TestPlatform/api_test_platform_demo/backend/do/__init__.py
2023-07-0400:38:57,648 INFO sqlalchemy.engine.Engine SELECT DATABASE()2023-07-0400:38:57,648 INFO sqlalchemy.engine.Engine [raw sql]{}2023-07-0400:38:57,661 INFO sqlalchemy.engine.Engine SELECT @@sql_mode
2023-07-0400:38:57,661 INFO sqlalchemy.engine.Engine [raw sql]{}2023-07-0400:38:57,667 INFO sqlalchemy.engine.Engine SELECT @@lower_case_table_names
2023-07-0400:38:57,668 INFO sqlalchemy.engine.Engine [raw sql]{}2023-07-0400:38:57,679 INFO sqlalchemy.engine.Engine BEGIN (implicit)2023-07-0400:38:57,680 INFO sqlalchemy.engine.Engine SELECT COUNT(*) FROM information_schema.tables WHERE table_schema =%(table_schema)s AND table_name =%(table_name)s
2023-07-0400:38:57,680 INFO sqlalchemy.engine.Engine [generated in0.00026s]{'table_schema':'testplatform','table_name':'user'}2023-07-0400:38:57,689 INFO sqlalchemy.engine.Engine
CREATE TABLE user (id INTEGER NOT NULL AUTO_INCREMENT,
username VARCHAR(64) NOT NULL,
password VARCHAR(128) NOT NULL,
PRIMARY KEY (id),
UNIQUE (username))2023-07-0400:38:57,689 INFO sqlalchemy.engine.Engine [no key 0.00021s]{}2023-07-0400:38:57,773 INFO sqlalchemy.engine.Engine COMMIT
Process finished with exit code 0