In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "python django transaction instance source code analysis", the explanation content in the article is simple and clear, easy to learn and understand, please follow the idea of Xiaobian slowly in-depth, together to study and learn "python django transaction instance source code analysis"!
python Django transactions # atomic() method # from django.db import transaction#################### atomic()###################def atomic(using=None, savepoint=True): #Decorators and context managers must. () calls a method because the real 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)############################################ self.using = using self.savepoint = savepoint def __enter__(self): connection = get_connection(self.using) sid = connection.savepoint() #Enter with 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) #Submit a transaction except DatabaseError: try: connection.savepoint_rollback(sid) #Capture database exception rollback connection.savepoint_commit(sid) except Error: connection.needs_rollback = True raise ##There is also a section of code exec_type Global rollback when receiving exceptions from other programs, omitted here # do.................################################ ContextDecorator#################################class ContextDecorator(object): def __call__(self, func): def inner(*args, **kwargs): with self: #Put the function into self with context manager, the effect is the same with, but the control granularity is different return func(*args, **kwargs) return innerpython MySQLdbclass Tran(): def __init__(self, conn=None, close=True): if conn is None: #Create database links print 'init' self.conn = conn_tbkt() self.cur = self.conn.cursor() self.sql = [] def __enter__(self): #Context Manager returns 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.execute(s) self.conn.commit() except: #All exceptions can be caught (django transactions cannot be rolled back if program abort occurs in the middle) try: #rollback itself is sql execution and may 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:#in transaction block @atomic() or with atomic():sid = transaction.savepoint ('tbkt_pxb') try: # do... except: transaction.savepoint_rollback(sid, 'tbkt_pxb')
Note: If there are multiple databases with routes, you need to specify and route to return consistent using: model under math3 needs transactions, even if ziyuan_new and default are the same library, you must use using =ziyuan_new
ziyuan_app = ['math3', 'ziyuan'] if model._ meta.app_label in ziyuan_app: return "ziyuan_new" return 'default'
Call time must. () method call
You must be careful about the use of try in atomic blocks. If you manually catch a program error, the atomic wrapper will miss the exception and will not roll back. Either the code in the try does not affect the transaction operation, or raise it after catching the exception, so that atomic can roll back normally (because I did not notice this problem, I tried for several days without success, remember)
Thank you for reading, the above is the content of "python django transaction instance source code analysis", after learning this article, I believe that everyone has a deeper understanding of python django transaction instance source code analysis, and the specific use needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.