Search code examples
pythontwisted

Twisted adbapi.ConnectionPool doesnt do anything


I try to use code below:

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')")

But data not inserted in mysql, also no error is shown. Data to connection is well.


Solution

  • You need to start the reactor. the "a" in adbapi is for "asynchronous", like just about everything else in twisted. When you call ConnectionPool.runQuery(), you have asked twisted to do some work in the background, and when it is done, give you the result of that action in the deferred returned by runQuery.

    But for twisted to "do" anything, you are obligated to start its event loop. In the very simplest case, you could:

    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()