網(wǎng)上關(guān)于django1.6的事務(wù)資料很多,但是1.8的卻搜不到任何資料,自己要用的時(shí)候費(fèi)了不少勁就是不行,現(xiàn)在記下要用的人少走彎路 version:Django 1.8 事務(wù)官方文檔 事務(wù)中文文檔 里面介紹很多方法,不一一贅述,按照文檔即可,下面只分析下atomic方法的源碼 按照官方文檔 transaction.atomic 有兩種用法裝飾器和上下文管理器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
# atomic() 方法 # from django.db import transaction ################### # atomic() ################### def atomic(using = None , savepoint = True ): # 裝飾器和上下文管理器必須.()調(diào)用方法,因?yàn)檎嬲奶幚硎窃摲椒ǚ祷氐膶?shí)例,不是該方法本身 if callable (using): return Atomic(DEFAULT_DB_ALIAS, savepoint)(using) # Decorator: @atomic(...) or context manager: with atomic(...): ... else : return Atomic(using, savepoint) ########################################## # Atomic類 省略了非核心內(nèi)容 ############################################ 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() # 進(jìn)入with創(chuàng)建一個(gè)保存點(diǎn) # .............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) # 提交事務(wù) except DatabaseError: try : connection.savepoint_rollback(sid) # 捕獲數(shù)據(jù)庫異常回滾 connection.savepoint_commit(sid) except Error: connection.needs_rollback = True raise ## 還有一段代碼是exec_type收到其他程序異常時(shí)候 全局回滾,此處省略 # do................. ############################### # ContextDecorator ################################# class ContextDecorator( object ): def __call__( self , func): def inner( * args, * * kwargs): with self : # 把函數(shù)放進(jìn)self的with上下文管理器,效果with相同,只是控制細(xì)粒度不同 return func( * args, * * kwargs) return inner |
python MySQLdb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
class Tran(): def __init__( self , conn = None , close = True ): if conn is None : # 創(chuàng)建數(shù)據(jù)庫鏈接 print 'init' self .conn = conn_tbkt() self .cur = self .conn.cursor() self .sql = [] def __enter__( self ): # 上下文管理器返回 sql語句列表 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 # 執(zhí)行sql for s in self .sql: self .cur.execute(s) self .conn.commit() except : # 可以捕獲所有異常(django事務(wù)如果中間出現(xiàn)程序異常終止無法回滾) try : # 回滾本身也是sql執(zhí)行,也有可能失敗 import traceback traceback.print_exc() print 'rollback' self .conn.rollback() except : print u '回滾失敗' finally : self .cur.close() self .conn.close() |
更細(xì)粒度的回滾:
1
2
3
4
5
6
|
# 在事務(wù)塊中@atomic() 或者 with atomic(): sid = transaction.savepoint( 'tbkt_pxb' ) try : # do .......... except : transaction.savepoint_rollback(sid, 'tbkt_pxb' ) |
注意:如果有多個(gè)數(shù)據(jù)庫有路由,則需要指定和路由返回一致的useing: math2下的model需要事務(wù),即使ziyuan_new和default是同一個(gè)庫,也必須使用useing=ziyuan_new
1
2
3
4
5
|
ziyuan_app = [ 'math2' , 'ziyuan' ] if model._meta.app_label in ziyuan_app: return "ziyuan_new" return 'default' |
調(diào)用時(shí)候必須.()方法調(diào)用
atomic塊中必須注意try的使用,如果手動(dòng)捕獲了程序錯(cuò)誤會(huì)導(dǎo)致atomic包裝器捕獲不到異常,也就不會(huì)回滾。要么try內(nèi)代碼不影響事務(wù)操作,要么就捕獲異常后raise出,讓atomic可以正常回滾(就是因?yàn)闆]有注意到這個(gè)問題,導(dǎo)致嘗試了好幾天都沒成功,切記)
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
原文鏈接:https://my.oschina.net/watcher/blog/718449