创建user表实体类
- 新增do目录下创建user_entity.py和init.py
from sqlalchemy import Integer
from server import db
"""
User表的实体类,与DB字段一致
"""
class UserEntity(db.Model):
# 表名, 需要重新命名,默认按类名来创建表名
__tablename__ = "user"
# 唯一主键ID
id = db.Column(Integer,primary_key=True)
# 用户名,唯一,不可为空
username = db.Column(db.String(64), nullable=False, unique=True)
# 密码,不为空
password = db.Column(db.String(128), nullable=False)
def user_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-04 00:38:57,648 INFO sqlalchemy.engine.Engine SELECT DATABASE()
2023-07-04 00:38:57,648 INFO sqlalchemy.engine.Engine [raw sql] {}
2023-07-04 00:38:57,661 INFO sqlalchemy.engine.Engine SELECT @@sql_mode
2023-07-04 00:38:57,661 INFO sqlalchemy.engine.Engine [raw sql] {}
2023-07-04 00:38:57,667 INFO sqlalchemy.engine.Engine SELECT @@lower_case_table_names
2023-07-04 00:38:57,668 INFO sqlalchemy.engine.Engine [raw sql] {}
2023-07-04 00:38:57,679 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-07-04 00: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-04 00:38:57,680 INFO sqlalchemy.engine.Engine [generated in 0.00026s] {'table_schema': 'testplatform', 'table_name': 'user'}
2023-07-04 00: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-04 00:38:57,689 INFO sqlalchemy.engine.Engine [no key 0.00021s] {}
2023-07-04 00:38:57,773 INFO sqlalchemy.engine.Engine COMMIT
Process finished with exit code 0
-
查看数据库中是否创建成功
文章来源:https://www.toymoban.com/news/detail-516581.html
user表以及字段创建成功啦,以此类推所有的实体类一次性写好一起创建文章来源地址https://www.toymoban.com/news/detail-516581.html
到了这里,关于测试开发-后端开发do实体类创建的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!