Defer function call till after transaction
I've been getting my hands dirty with tortoise recently, and I have been loving it. Porting from Django, I noticed (not sure if it isn't implemented already but with a different name) that I could not find something similar to transaction.on_commit in Django, something I could use to run comment only if the current transaction block is committed. I could easily go round this by moving the function call down, but in cases involving multiple models in different modules, that might up my imports and make my code more tightly coupled. The solution must not completely mirror Django, as tortoise is not Django, but could be something similar.
You can just wrap the transaction like this:
class Transaction:
async def __aenter__(self):
self.connection = in_transaction()
await self.connection.__aenter__()
return self.connection
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.connection.__aexit__(exc_type, exc_val, exc_tb)
if not exc_type:
# Do something on success
pass
async with Transaction() as connection:
pass
An on_commit hook is basic stuff for any orm used in production, without this my celery tasks are in a race condition with the commit. This belongs in the orm imo