Introduction to pythondjango transaction source code analysis

Source: Internet
Author: User
This article mainly introduces detailed information about python django transaction source code analysis. For more information, see the next article. it mainly introduces detailed information about python django transaction source code analysis, for more information, see

Python Django transactions

There are a lot of online transaction information about django1.6, but 1.8 cannot find any information. if you have to use it for a long time, you will not be able to use it. now you can write down the version with fewer detours: many methods are introduced in the Chinese documents of Django 1.8 official transactions. do not repeat them one by one. follow the instructions below to analyze only the source code of the atomic method according to the official documents transaction. there are two ways to use atomic: decorator and context manager.

# Atomic () method # from django. db import transaction ################### atomic () ################## def atomic (using = None, savepoint = True): # required for decorator and context manager. () call the method, because the actual processing is the instance returned by the method, not the method itself if callable (using): return Atomic (DEFAULT_DB_ALIAS, savepoint) (using) # Decorator: @ atomic (...) or context manager: with atomic (...) :... else: return Atomic (using, savepoint) ######################################## ### non-core content is omitted in the Atomic class ############################### ############ class Atomic (ContextDecorator): def init (self, using, savepoint): self. using = using self. savepoint = savepoint def enter (self): connection = get_connection (self. using) sid = connection. savepoint () # enter with to create a save point #............. do def exit (self, exc_type, exc_value, traceback): if connection. in_atomic_block: # do ............. if sid is not None: try: connection. savepoint_commit (sid) # commit the transaction commit T DatabaseError: try: connection. savepoint_rollback (sid) # capture database exceptions and roll back the connection. savepoint_commit (sid) failed t Error: connection. needs_rollback = True raise # Another piece of code is exec_type, which is global rollback when other program exceptions are received, skipped here # do ................. ############################### ContextDecorator ####### ######################### class ContextDecorator (object): def call (self, func): def inner (* args, ** kwargs): with self: # put the function into the with context manager of self, with the same effect, only fine-grained control of different return func (* args, ** kwargs) return inner

Python MySQLdb

Class Tran (): def init (self, conn = None, close = True): if conn is None: # create a database link print 'init' self. conn = conn_tbkt () self. cur = self. conn. cursor () self. SQL = [] def enter (self): # The context manager returns the SQL statement list with Tran ('tbkt _ pxb') as sqls: print 'enter' return self. SQL # SQL. append ('select 1') def exit (self, exc_type, exc_val, exc_tb): print 'exit 'try: print self. SQL # execute SQL for s in self. SQL: self.cur.exe cute (s) self. conn. commit () commit T: # all exceptions can be caught (if a program exception occurs in the middle of a django transaction, it cannot be rolled back) try: # Rollback itself is also an SQL execution, it may also fail to import traceback. print_exc () print 'rollback' self. conn. rollback () failed t: print u'rollback failed' finally: self. cur. close () self. conn. close ()

More fine-grained rollback:

# @ Atomic () or with atomic (): sid = transaction in the transaction block. savepoint ('tbkt _ pxb') try: # do .......... counter T: transaction. savepoint_rollback (sid, 'tbkt _ pxb ')

Note: If multiple databases have routes, you need to specify the useing that is the same as that returned by the route: the model under math2 requires a transaction, even if ziyuan_new and default are the same database, you must also use useing = ziyuan_new

  ziyuan_app = ['math2', 'ziyuan']  if model._meta.app_label in ziyuan_app:   return "ziyuan_new"  return 'default'

The. () method is required for call.

Note the use of try in the atomic block. if a program error is manually captured, the atomic package cannot catch the exception and will not roll back. Either the code in try does not affect the transaction operation, or raise will be caught after the exception, so that the atomic can be rolled back normally (that is, due to the failure to notice this problem, it has failed for several days, remember)

Thank you for reading this article. I hope it will help you. thank you for your support for this site!

The above is a detailed introduction to python django transaction source code analysis. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.