Transaction beginning in Django
I read the chapter in the Django docs about the transaction management. From what I understand, the transaction is started as soon as TransactionMiddleware
is invoked. Then by using @commit_on_success
, @commit_manually
there is a possibility of controlling transaction ending.
My question: is there a possibility to control transaction beginning as well without getting rid of TransactionMiddleware altogether. My concern is that many parts of Django framework actually depend on TransactionMiddleware presence, so I don't really want to break it. I'd like it to be used for all the views except for those that b开发者_如何学Goelong to the applications that I explicitly specify. Most of all I'd like to be able to control transactional behaviour for certain group of views totally - from the beginning until the end. What approach should I take? Are there any external apps, libraries to help me out? Are transactions created eagerly or lazily - as soon as the first database hit occurs?
Transactions are created with first DB query.
TransactionMiddleware
applies something similar tocommit_on_success
to all your views. There's no need to add this explicitly.commit_on_success
is still useful for giving this behavior to specific functions you call from within a view.Nested transactions are supported.
So, why do you need to control transaction start? If you want to rollback just part of changes, this should be done using nested transactions.
Here's common use case from my code:
@transaction.commit_manually
def purchase(request, ...):
try:
... # change some data
_purchase(request, *args, **kwargs) # process purchase optimistically
except PurchaseError, ex: # My own exception class for errors we know about
_log_purchase(request, ex) # Save error in DB
messages.error(ex.human_message())
transaction.commit() # Save log entries
except:
transaction.rollback()
raise
else:
transaction.commit()
@transaction.commit_on_success
def _purchase(request, ...):
...
精彩评论