python
  • twisted
  • 2012-12-27 113 views 2 likes 
    2

    我嘗試使用下面的代碼:扭曲adbapi.ConnectionPool沒有做任何事情

    from twisted.enterprise import adbapi 
    
        dbpool = adbapi.ConnectionPool(
             "MySQLdb", 
             db='test_db', 
             port='3306', 
             user='tester', 
             passwd='some_pass', 
             host='localhost', 
             cp_reconnect=True 
            ) 
    
        dbpool.runQuery("INSERT INTO `htp_test` VALUES(NULL, 25, 'test')") 
    

    但數據不能在MySQL中插入,也沒有顯示任何錯誤。數據連接很好。

    +0

    您是否需要啓動反應堆? – SingleNegationElimination

    +0

    爲什麼我需要啓動它? – Sever

    回答

    3

    您需要啓動反應器。 adbapi中的「a」用於「異步」,就像扭曲的其他所有內容一樣。當你打電話給ConnectionPool.runQuery()時,你已經要求在後臺進行一些工作,並且在完成後,給你在延期中由runQuery返回的那個動作的結果。

    但是,爲了扭曲「做」任何事情,您有義務啓動其事件循環。在最簡單的情況下,您可以:

    from twisted.internet import reactor 
    from twisted.enterprise import adbapi 
    
    def got_result(value): 
        # do something, value won't be interesting on insert statements, though 
        print "Horray"  
        # since this is all we want to do, stop the reactor 
        reactor.stop() 
    
    d = dbpool.runQuery("INSERT INTO `htp_test` VALUES(NULL, 25, 'test')") 
    d.addCallback(got_result) 
    
    reactor.run() 
    
    +1

    我應該注意,你只需要做一個簡短的腳本。在任何大型Twisted系統或應用程序中,如果這個代碼正在執行某些其他操作,那麼反應器應該已經在運行。反應器只能在程序中運行一次。 – Glyph

    相關問題