如何使用 tortoise-orm 运行 简单的脚本?

How to run simple scripts using tortoise-orm?

如何 运行 连接数据库并在 tortoise-orm 中执行查询的简单脚本?

如果您运行正在编写一个简单的脚本,您可以这样做,

from tortoise import Tortoise

async def init():
    # Here we create a SQLite DB using file "db.sqlite3"
    #  also specify the app name of "models"
    #  which contain models from "app.models"
    await Tortoise.init(
        db_url='sqlite://db.sqlite3',
        modules={'models': ['app.models']}
    )
    # Generate the schema (run this only if you need to generate the schema)
    # await Tortoise.generate_schemas()

run_async(init())

run_async 是 运行 简单异步 Tortoise 脚本的辅助函数。如果您运行将 Tortoise ORM 作为服务的一部分,请从 Tortoise ORM 文档中正确查看 The Importance of cleaning up