aerich迁徙tortoise-orm数据库教程

打印 上一主题 下一主题

主题 1878|帖子 1878|积分 5634

aerich迁徙tortoise-orm数据库教程
目次
1.介绍
2.问题
3.tortoise-orm 自身函数迁徙数据库
4.aerich命令迁徙tortoise-orm数据库表
5.aerich代码迁徙tortoise-orm数据库表
6. 留意事项(总结)


1.介绍

        tortoise-orm是异步orm,语法类似django-orm,非常简单方便;一般配合fastapi利用。
        tortoise-orm自身有generate_schemas函数用于数据库表创建
        但实际项目开辟中利用较少,多用aerich来迁徙model->数据库表
2.问题

        aerich 0.8.0和0.8.1 版本 cmd执行命令 存在问题,aerich init-db  upgrade等命令执行后 无法退出。
        缘故原由:0.7.2以上版本,默认一直连接数据库(config里面有数据库连接路径),命令端无法退出连接,因此在代码程序中接纳aerich Command执行命令,须要lifespan中Tortoise.close_connections
https://fastapi.tiangolo.com/zh/advanced/events/?h=lifespan#lifespan

        aerich 0.7.2版本 没有问题
3.tortoise-orm 自身函数迁徙数据库

        建议看官网代码(点击查看),直接上代码,必须2个py文件(model单独1个py文件,main 1个文件),这样才不会报错
        Tortoise.init(db_url="sqlite://db.sqlite3", modules={"models": ["test"]})中 `models`可以改成任意名字,然后model表中外键、多对多须要改成对应名字.表名【models改成model,那么models.Clas须要改成model.Clas】,test为model表py模块(既可以是py文件也但是文件夹)
  1. # test.py
  2. from tortoise import fields, models, Tortoise
  3. from enum import IntEnum
  4. class AbstractModel(models.Model):
  5.     id = fields.UUIDField(primary_key=True, unique=True, db_index=True)
  6.     createdAt = fields.DatetimeField(auto_now_add=True, null=True)
  7.     updatedAt = fields.DatetimeField(auto_now=True, null=True)
  8.     class Meta:
  9.         abstract = True
  10. class Gender(IntEnum):
  11.     MAN = 0
  12.     WOMAN = 1
  13. class Student(AbstractModel):
  14.     name = fields.CharField(max_length=100, db_index=True, description="姓名")
  15.     gender = fields.IntEnumField(Gender, description="性别")
  16.     age = fields.IntField(description="年龄")
  17.     clas = fields.ForeignKeyField("models.Clas", related_name="students", description="班级外键")
  18. class Clas(AbstractModel):
  19.     name = fields.CharField(max_length=200, db_index=True, description="班级名称")
  20.    
复制代码
  1. # main.py
  2. from tortoise import Tortoise, run_async
  3. from test import Student, Clas
  4. async def run():
  5.     await Tortoise.init(db_url="sqlite://db.sqlite3", modules={"models": ["test"]})
  6.     await Tortoise.generate_schemas()
  7.     clas1 = await Clas.create(name="一年级一班1")
  8.     stu = await Student.create(name="gyl", gender=1, age=30, clas=clas1)
  9.     print(await Student.all().values())
  10.     s = await Student.first().values()
  11.     print(s['id'])
  12.     print(s.keys())
  13. if __name__=="__main__":
  14.     run_async(run())
复制代码
4.aerich命令迁徙tortoise-orm数据库表

        利用版本为0.7.2,参考aerich官网(点击查看)命令,对于TORTOISE_ORM参数官网(点击查看)
        aerich命令
        aerich init -t config.TORTOISE_ORM     一般执行1次
        aerich init-db     一般执行1次
        aerich migrate     修改表就执行
        aerich upgrade (aerich downgrade)
TORTOISE_ORM配置参数
  1. # 一般需要将 connections中的key 改成default 对应default_connection
  2. '''
  3. 注意:TORTOISE_ORM中
  4.         "apps": {
  5.             "modelApp": {
  6.                 "models": ["models", "aerich.models"],  # models里面有__init__.py就不需要再.了
  7.                 "default_connection": "default" # 对应connections里面的
  8.             }
  9.         },
  10.         
  11.         `modelApp`(key) 是定义表外键、多对多时 “{app}.{table_name}”中的app, 若modelApp重命名, 则外键里面的app也改成对应的名字 clas = fields.ForeignKeyField("modelApp.Clas", related_name="students")
  12.         `[]`里面的`models`是指的py模块路径(相对路径) 对于多级嵌套的的models文件夹 建议设置添加__init__.py导入所有表, 外键等就可以 modelApp."表名" 然后初始化创建表时 自动跟踪模块下面的所有table
  13. '''
  14. TORTOISE_ORM: dict = {
  15.     "connections": {
  16.         # SQLite configuration
  17.         # "sqlite": {
  18.         #     "engine": "tortoise.backends.sqlite",
  19.         #     "credentials": {"file_path": f"{具体路径}/db.sqlite3"},  # Path to SQLite database file
  20.         # },
  21.         # MySQL/MariaDB configuration
  22.         # Install with: tortoise-orm[asyncmy]
  23.         # "mysql": {
  24.         #     "engine": "tortoise.backends.mysql",
  25.         #     "credentials": {
  26.         #         "host": "localhost",  # Database host address
  27.         #         "port": 3306,  # Database port
  28.         #         "user": "yourusername",  # Database username
  29.         #         "password": "yourpassword",  # Database password
  30.         #         "database": "yourdatabase",  # Database name
  31.         #     },
  32.         # },
  33.         # PostgreSQL configuration
  34.         # Install with: tortoise-orm[asyncpg]
  35.         # "postgres": {
  36.         #     "engine": "tortoise.backends.asyncpg",
  37.         #     "credentials": {
  38.         #         "host": "localhost",  # Database host address
  39.         #         "port": 5432,  # Database port
  40.         #         "user": "yourusername",  # Database username
  41.         #         "password": "yourpassword",  # Database password
  42.         #         "database": "yourdatabase",  # Database name
  43.         #     },
  44.         # },
  45.         # MSSQL/Oracle configuration
  46.         # Install with: tortoise-orm[asyncodbc]
  47.         # "oracle": {
  48.         #     "engine": "tortoise.backends.asyncodbc",
  49.         #     "credentials": {
  50.         #         "host": "localhost",  # Database host address
  51.         #         "port": 1433,  # Database port
  52.         #         "user": "yourusername",  # Database username
  53.         #         "password": "yourpassword",  # Database password
  54.         #         "database": "yourdatabase",  # Database name
  55.         #     },
  56.         # },
  57.         # SQLServer configuration
  58.         # Install with: tortoise-orm[asyncodbc]
  59.         # "sqlserver": {
  60.         #     "engine": "tortoise.backends.asyncodbc",
  61.         #     "credentials": {
  62.         #         "host": "localhost",  # Database host address
  63.         #         "port": 1433,  # Database port
  64.         #         "user": "yourusername",  # Database username
  65.         #         "password": "yourpassword",  # Database password
  66.         #         "database": "yourdatabase",  # Database name
  67.         #     },
  68.         # },
  69.     },
  70.     'apps': {
  71.         'models': {
  72.             'models': ['models', 'aerich.models'], # []中的models为 表 模块(models.py或者models文件夹模块 需要有__init__.py导入表)
  73.             # If no default_connection specified, defaults to 'default'
  74.             'default_connection': 'default',
  75.         }
  76.     }
  77. }
复制代码
5.aerich代码迁徙tortoise-orm数据库表

        版本利用0.8.1
        代码迁徙,确保tortoise关闭连接,这样就不会出现代码执行后 无法退出的现象
  1. from aerich import Command
  2. from config import settings
  3. from tortoise import Tortoise
  4. async def init_db():
  5.     # settings.TORTOISE_ORM参考第4节
  6.     command = Command(tortoise_config=settings.TORTOISE_ORM)
  7.     # try:
  8.     #     await command.init_db(safe=True)
  9.     # except FileExistsError:
  10.     #     pass
  11.     await command.init()  # 对应aerich init -t
  12.     try:
  13.         await command.init_db(safe=True)  # 对应aerich init-db
  14.     except FileExistsError:
  15.         pass
  16.     try:
  17.         await command.migrate()  # 对应aerich migrate
  18.     except AttributeError:
  19.         pass
  20.     await command.upgrade(run_in_transaction=True)  # 对应aerich upgrade
  21. async def lifespan():
  22.     await init_db()
  23.     await Tortoise.close_connections()  # 执行完成后 关闭Tortoise连接,即关闭数据库连接,像sqlite shm wal文件才会消失,不可直接删除,否则数据库没有数据
  24. import asyncio
  25. asyncio.run(lifespan())
复制代码
6. 留意事项(总结)

        [1] 若接纳aerich cmd端命令执行数据库创建、迁徙,那么代码中推荐接纳from tortoise.contrib.fastapi import register_tortoise,register_tortoise中generate_schemas调用的tortoise本身的函数迁徙(不推荐生产利用,没有迁徙记载);
        [2] 若接纳aerich Command 代码程序,那么须要Fastapi中的lifespan,执行关闭数据库连接;
        [3] 现在个人接纳[1]的aerich cmd命令端执行迁徙,然后register_tortoise注册;[1]和[2]不要同时利用,背面可利用[2]




免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

商道如狼道

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表