Easy async ORM for Python, built with relations in mind
Database transaction support for ensuring data consistency across multiple operations. Provides both context manager and decorator approaches for transaction handling.
Context manager for running code within a database transaction.
from tortoise.transactions import in_transaction
def in_transaction(connection_name=None):
"""
Transaction context manager.
Run code inside async with in_transaction() to execute within one transaction.
If error occurs, transaction will rollback.
Args:
connection_name (str, optional): Name of connection to use.
Required if multiple databases configured.
Returns:
TransactionContext: Context manager for transaction
"""Decorator for wrapping functions in database transactions.
from tortoise.transactions import atomic
def atomic(connection_name=None):
"""
Transaction decorator.
Wrap functions with this decorator to run them within one transaction.
If function raises exception, transaction will rollback.
Args:
connection_name (str, optional): Name of connection to use.
Required if multiple databases configured.
Returns:
Function decorator for transaction handling
"""from tortoise.transactions import in_transaction
from myapp.models import User, Profile
async def create_user_with_profile():
async with in_transaction():
# All operations within this block run in same transaction
user = await User.create(name="Alice", email="alice@example.com")
profile = await Profile.create(user=user, bio="Software Engineer")
# If any operation fails, entire transaction rolls back
return userfrom tortoise.transactions import atomic
from myapp.models import User, Order
@atomic()
async def process_order(user_id, items):
"""Process order atomically."""
user = await User.get(id=user_id)
# Deduct balance
total_cost = sum(item.price for item in items)
if user.balance < total_cost:
raise ValueError("Insufficient balance")
user.balance -= total_cost
await user.save()
# Create order
order = await Order.create(user=user, total=total_cost)
# If any step fails, all changes are rolled back
return orderfrom tortoise.transactions import in_transaction, atomic
# Specify connection for multiple database setup
async def multi_db_operation():
async with in_transaction("users_db"):
await User.create(name="Alice")
async with in_transaction("orders_db"):
await Order.create(total=100)
@atomic("analytics_db")
async def update_analytics():
# Transaction on specific database
await AnalyticsRecord.create(event="user_signup")Transactions automatically rollback when:
Tortoise ORM handles nested transactions using database savepoints:
async with in_transaction():
await User.create(name="Alice")
try:
async with in_transaction(): # Nested transaction (savepoint)
await User.create(name="Bob")
raise Exception("Something went wrong")
except:
pass # Inner transaction rolled back to savepoint
# Outer transaction continues
await User.create(name="Charlie") # This will still be committedconnection_name specified, uses default connectionconnection_name is requiredParamsError if connection specification is ambiguousInstall with Tessl CLI
npx tessl i tessl/pypi-tortoise-orm