Python tortoise-orm 模块:实用工具集

Python tortoise-orm 模块

tortoise-orm 是一个强大的异步 ORM(对象关系映射)库,旨在通过简单的代码构建与数据库的连接,使得操作数据库变得高效和轻松。它支持多种数据库,包括 SQLite、PostgreSQL、MySQL 等。tortoise-orm 与现代 Python 项目的兼容性极佳,支持异步操作,特别适用于使用异步框架(如 FastAPI、Sanic)的项目。支持 Python 版本包括 3.6 及以上。

应用场景

tortoise-orm 适用于需要与数据库进行复杂交互的 Python 应用,特别是在网络应用和微服务架构中,因其异步处理能力更是其一大优势。开发者可以利用 tortoise-orm 在数据存储、数据抽取、以及业务逻辑中的数据操作极大地简化代码,并提高应用的性能。

安装说明

tortoise-orm 并不是 Python 的内置模块,需要通过包管理工具进行安装。可以使用以下命令安装:

1
pip install tortoise-orm

此命令会自动从 Python 的包索引(PyPI)下载并安装 tortoise-orm 及其依赖。

用法举例

1. 示例一:基本创建与查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from tortoise import Tortoise, fields
from tortoise.models import Model

# 定义User模型
class User(Model):
id = fields.IntField(pk=True) # 主键字段
username = fields.CharField(max_length=50) # 用户名字段
email = fields.CharField(max_length=100) # 邮箱字段

async def run():
await Tortoise.init(
db_url='sqlite://db.sqlite3', # 使用SQLite数据库
modules={'models': ['__main__']}, # 注册模型
)
await Tortoise.generate_schemas() # 生成数据库表

# 创建一个用户实例
user = await User.create(username='john_doe', email='john@example.com') # 创建用户
print(user.id, user.username) # 打印用户信息

# 查询所有用户
users = await User.all() # 查询所有用户
for user in users:
print(user.username) # 打印每个用户的用户名

# 运行代码

2. 示例二:更新与删除

1
2
3
4
5
6
7
8
9
10
11
async def update_and_delete():
# 查询用户
user = await User.get(username='john_doe') # 获取用户名为john_doe的用户
user.email = 'john_doe_updated@example.com' # 更新用户邮箱
await user.save() # 保存更新

# 删除用户
await user.delete() # 删除该用户
print(f'User {user.username} deleted.') # 打印删除信息

# 运行代码

3. 示例三:事务处理

1
2
3
4
5
6
7
8
9
10
11
12
async def transaction_example():
async with Tortoise.transaction(): # 开始事务
user1 = await User.create(username='user1', email='user1@example.com') # 创建第一个用户
user2 = await User.create(username='user2', email='user2@example.com') # 创建第二个用户

if some_condition: # 根据某个条件决定
raise Exception("Something went wrong!") # 模拟异常,回滚事务

# 如果没有异常,事务会自动提交
print("Transaction completed successfully.") # 打印事务成功信息

# 运行代码

软件和库版本不断更新

由于软件和库版本不断更新,如果本文档不再适用或有误,请留言或联系我进行更新。让我们一起营造良好的学习氛围。感谢您的支持! - Travis Tang

我非常欢迎大家关注我的博客全糖冲击博客,在这里,您将找到所有 Python 标准库的实用教程,这将极大地帮助您在 Python 编程的学习和应用。我的博客具有丰富的内容、清晰的结构和实用的示例,帮助您更快地掌握 Python 的各项技能,提升您的编程能力。如果您希望在学习中少走弯路,找到高效的学习资源和技巧,请务必关注我!