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
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', 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') 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 的各项技能,提升您的编程能力。如果您希望在学习中少走弯路,找到高效的学习资源和技巧,请务必关注我!