|
创建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表以及字段创建成功啦,以此类推所有的实体类一次性写好一起创建
来源:https://www.cnblogs.com/hnfangh/p/17524587.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作! |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
x
|