文章目录
Tortoise ORM
一、 简介
1、 ORM
当您构建使用关系数据库的应用程序或服务时,有时您不能仅仅使用参数化查询甚至查询构建器就可以逃脱,您只是不断重复自己,为每个实体编写略有不同的代码。代码不知道数据之间的关系,因此您最终几乎是手动连接数据。访问数据库的方式也很容易出错,从而很容易发生 SQL 注入攻击。您的数据规则也是分布式的,增加了管理数据的复杂性,更糟糕的是,应用不一致。
ORM(对象关系映射器)旨在解决这些问题,通过集中您的数据模型和数据规则,确保您的数据得到安全管理(提供对 SQL 注入的免疫力)并跟踪关系,因此您不必。
2、 介绍
Tortoise ORM 是受 Django 启发的易于使用的asyncio
ORM (对象关系映射器) 。
Tortoise ORM 的构建类似于 Django ORM。它的设计中不仅使用表格,还使用关系数据。
与其他 Python ORM 相比,它也表现良好,与 Pony ORM 进行交易:
官方文档地址:https://tortoise-orm.readthedocs.io/en/latest/index.html
3、 简单使用
创建模型:
from tortoise.models import Model
from tortoise import fields
class Tournament(Model):
id = fields.IntField(pk=True)
name = fields.TextField()
创建表,初始化数据库:
from tortoise import Tortoise, run_async
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
await Tortoise.generate_schemas()
# run_async is a helper function to run simple async Tortoise scripts.
run_async(init())
数据查询:
# Create instance by save
tournament = Tournament(name='New Tournament')
await tournament.save()
# Or by .create()
await Tournament.create(name='Another Tournament')
# Now search for a record
tour = await Tournament.filter(name__contains='Another').first()
print(tour.name)
4、 环境配置
pip install tortoise-orm
# 安装数据库驱动
pip install tortoise-orm[asyncpg]
pip install tortoise-orm[aiomysql]
pip install tortoise-orm[asyncmy]
# 除此之外,还支持:aiosqlite
二、 基础配置
1、 数据库链接
Tortoise 目前支持以下数据库:
- SQLite
- PostgreSQL >= 9.4(使用
asyncpg
) - MySQL/MariaDB(使用
aiomysql
)
要使用,请确保已安装asyncpg
和/或aiomysql
Tortoise 支持以 URL 形式指定数据库配置:
语法:
DB_TYPE://USERNAME:PASSWORD@HOST:PORT/DB_NAME?PARAM1=value&PARAM2=value
支持的DB_TYPE
:
-
sqlite
:通常以 So if the is “/data/db.sqlite3” 那么字符串将是(注意三个 /)
sqlite://{DB_FILE}
如:
sqlite:///data/db.sqlite
-
postgres
:通常采用以下形式:
postgres://postgres:pass@db.host:5432/somedb
-
mysql
:通常采用以下形式:
mysql://myuser:mypass:pass@db.host:3306/somedb
更详细的可以进入官方文档查看:https://tortoise-orm.readthedocs.io/en/latest/databases.html
2、 创建数据库
from tortoise import Tortoise, run_async
async def init():
# Here we create a SQLite DB using file "db.sqlite3"
# also specify the app name of "models"