2011-11-16 29 views
0

我有一個python腳本,可以全局調用mySQL的數據庫連接對象。有一個插入功能insertToTable(actionDate, action),它向表中插入一條記錄。 if __name__=="__main__":中的腳本的主要部分以無限的while循環運行數小時/天。python MySQLdb:hook函數來檢查連通性

問題是,MySQL連接對象可能會被閒置很多小時,導致MySQL服務器連接超時。我目前在函數內使用try & except來捕捉異常。然而,這會導致代碼重複,因爲我必須包含一個除block之外的try &來處理每個函數中的這個錯誤。

我想知道是否有一種Python機制,我可以將insertToTable()掛鉤到另一個函數,比如checkConnectivity()。當調用insertToTable()時,首先執行checkConnectivity(),然後繼續執行insertToTable()

回答

1

您可以創建一個調用checkConnectivity函數的裝飾器。例如:

def checkConnectivity(): 
    print 'Checking connection' 

def CheckConnectionDecorator(fn): 
    def new(*args, **kwargs): 
     checkConnectivity() 
     return fn(*args, **kwargs) 
    return new 

@CheckConnectionDecorator 
def insertToTable(): 
    print 'Insertion' 

@CheckConnectionDecorator 
def anotherQueryFunction(): 
    print 'Another query' 
+0

太棒了。這正是我想要的。 –