11"""
22This example demonstrates how you can use transactions with tortoise
3-
4- Currently tortoise doesn't have some kind of magic transaction wrapper
5- like django's transaction.atomic, but if you have to make something in transaction
6- you could still do it like this
73"""
84import asyncio
9- import sqlite3
105
116from tortoise import Tortoise , fields
12- from tortoise .backends .sqlite .client import SqliteClient
7+ from tortoise .transactions import in_transaction , atomic
8+ from tortoise .exceptions import OperationalError
139from tortoise .models import Model
14- from tortoise .utils import generate_schema
1510
1611
1712class Event (Model ):
@@ -26,19 +21,32 @@ def __str__(self):
2621
2722
2823async def run ():
29- client = SqliteClient ('example_transaction.sqlite3' )
30- await client .create_connection ()
31- Tortoise .init (client )
32- await generate_schema (client )
24+ await Tortoise .init (config_file = 'config.json' )
25+ await Tortoise .generate_schemas ()
3326
3427 try :
35- async with client . in_transaction () as connection :
28+ async with in_transaction () as connection :
3629 event = Event (name = 'Test' )
3730 await event .save (using_db = connection )
3831 await Event .filter (id = event .id ).using_db (connection ).update (name = 'Updated name' )
3932 saved_event = await Event .filter (name = 'Updated name' ).using_db (connection ).first ()
4033 await connection .execute_query ('SELECT * FROM non_existent_table' )
41- except sqlite3 .OperationalError :
34+ except OperationalError :
35+ pass
36+ saved_event = await Event .filter (name = 'Updated name' ).first ()
37+ print (saved_event )
38+
39+ @atomic ()
40+ async def bound_to_fall ():
41+ event = await Event .create (name = 'Test' )
42+ await Event .filter (id = event .id ).update (name = 'Updated name' )
43+ saved_event = await Event .filter (name = 'Updated name' ).first ()
44+ print (saved_event .name )
45+ raise OperationalError ()
46+
47+ try :
48+ await bound_to_fall ()
49+ except OperationalError :
4250 pass
4351 saved_event = await Event .filter (name = 'Updated name' ).first ()
4452 print (saved_event )
0 commit comments