python
  • twisted
  • 2012-12-27 118 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

    相关问题