#33882: Allow transaction.atomic to work in async contexts.
-------------------------------------+-------------------------------------
Reporter: alex | Owner:
| rajdesai24
Type: New feature | Status: assigned
Component: Database layer | Version: 4.0
(models, ORM) |
Severity: Normal | Resolution:
Keywords: async | Triage Stage: Accepted
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by rajdesai24):
Hey guys, I wanted to get your suggestion on this as I had been working on
this and testing it out
{{{
class AsyncAtomic:
def __init__(self, using=None, savepoint=True, durable=True):
self.using = using
self.savepoint = savepoint
self.durable = durable
async def __aenter__(self):
self.atomic = transaction.Atomic(self.using, self.savepoint,
self.durable)
await sync_to_async(self.atomic.__enter__)()
return self.atomic
async def __aexit__(self, exc_type, exc_value, traceback):
await sync_to_async(self.atomic.__exit__)(exc_type, exc_value,
traceback)
}}}
----
{{{
class AsyncAtomicTestCase(TestCase):
async def test_atomic(self):
async with AsyncAtomic():
# Create a new object within the transaction
await sync_to_async(SimpleModel.objects.create)(
field=4,
created=datetime(2022, 1, 1, 0, 0, 0),
)
# Verify that the object was created within the transaction
count = await sync_to_async(SimpleModel.objects.count)()
self.assertEqual(count, 1)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/33882#comment:11>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/010701866158b2ce-4c87f345-5dc3-4a32-ab06-6f21dfe92bb1-000000%40eu-central-1.amazonses.com.