About Python Django transaction transaction source code Analysis Introduction

Source: Internet
Author: User
Tags savepoint
This article mainly introduces the Python Django transaction transaction source code Analysis of the relevant information, the need for friends can refer to the following

Python Django Transaction

Online about django1.6 Business information a lot, but 1.8 but not any information, their own time to use a lot of effort is not, now write down the people to use less detours Version:django 1.8 Official document transactions in Chinese documents introduced a lot of methods, do not repeat, According to the document, the following only analysis under the atomic method of the source code according to the official document Transaction.atomic there are two usages of adorner and context manager

# Atomic () method # from Django.db import transaction#################### Atomic () ################## #def Atomic (Using=none, savepoint=true): # Adorner and context manager must. () 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) ############################# ############## Atomic class omits non-core content ########################################### #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 savepoint # .... 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) # commits a transaction excep T DatabaseError:try:connection.savepoint_rollback (SID) # captures database exception rollback CONNECTION.SAVEPOINT_COMMIT (SID) except ERR    OrConnection.needs_rollback = True Raise # # There is also a section of code that exec_type receive other program exceptions when global rollback, omitted # do.................################## ############## contextdecorator################################ #class Contextdecorator (object): Def call (self, func  ): Def inner (*args, **kwargs): With self: # put the function into the self's with context manager, with the same effect, just control the fine granularity of the different return func (*args, **kwargs) return inner

Python mysqldb

Class Tran (): Def init (self, Conn=none, close=true):  If Conn is None:     # CREATE DATABASE link   print ' init '   self.conn = C Onn_tbkt ()   self.cur = Self.conn.cursor ()   self.sql = [] def enter (self):       # The context manager returns a list of SQL statements with Tran (' Tbkt_ Pxb ') as Sqls:  print ' Enter '  return self.sql  # sql.append (' Select 1 ') def exit (self, exc_type, Exc_val, exc_t b):  print ' exit '  try:   print self.sql        # Execute SQL for   s in Self.sql:    Self.cur.execute (s)   self.conn.commit ()  except:            # can catch all exceptions (Django transaction if the program abnormally terminates in the middle cannot be rolled back)   try:     # rollback itself is also SQL execution, It is also possible to fail    import Traceback    traceback.print_exc ()    print ' rollback '    self.conn.rollback ()   Except:    print U ' rollback failed '  finally:   self.cur.close ()   self.conn.close ()

Finer-grained rollback:

# @atomic () or with atomic () in the transaction block: SID = Transaction.savepoint (' tbkt_pxb ') Try: # do ... except: Transaction.savepoint_rollback (SID, ' TBKT_PXB ')

Note: If there are multiple databases that have routes, you need to specify and route the model to return a consistent useing:math2 transaction, even if Ziyuan_new and default are the same library, you must use Useing=ziyuan_new

  Ziyuan_app = [' math2 ', ' Ziyuan ']  if Model._meta.app_label in Ziyuan_app:   return ' ziyuan_new '  return ' Default

Call time must. () method call

Atomic block must be aware of the use of try, if you manually catch a program error will cause the atomic wrapper to catch the exception, will not be rolled back. Either the in-try code does not affect the transaction operation, or catch the exception after raise out, so that atomic can be normal rollback (because the problem is not noticed, resulting in a few days of trying to succeed, remember)

Thank you for reading, hope to help everyone, thank you for the support of this site!

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.