开发者

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?


  1. Transactions are created with first DB query.

  2. TransactionMiddleware applies something similar to commit_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.

  3. 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, ...):
    ...  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜