测试开发-后端开发do实体类创建

创建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
  • 查看数据库中是否创建成功

user表以及字段创建成功啦,以此类推所有的实体类一次性写好一起创建

热门相关:倾心之恋:总裁的妻子   重生野性时代   花月颂   变身蜘蛛侠   天神诀