Twisted 是一个异步网络框架, 意味着标准数据库模块无法直接使用, 因为一般会这样来使用其接口:
# 创建连接... db = dbmodule.connect('mydb', 'andrew', 'password') # ...which blocks for an unknown amount of time # 创建游标 cursor = db.cursor() # 进行查询... resultset = cursor.query('SELECT * FROM table WHERE ...') # ...持续一段较长的时间,乃至数分钟
# 等价于 cursor.execute(statement), return cursor.fetchall(): def getAge(user): return dbpool.runQuery("SELECT age FROM users WHERE name = ?", user) def printResult(l): if l: print l[0][0], "years old" else: print "No such user" getAge("joe").addCallback(printResult)
def _getAge(txn, user): # this will run in a thread, we can use blocking calls txn.execute("SELECT * FROM foo") # ... other cursor commands called on txn ... txn.execute("SELECT age FROM users WHERE name = ?", user) result = txn.fetchall() if result: return result[0][0] else: return None def getAge(user): return dbpool.runInteraction(_getAge, user) def printResult(age): if age != None: print age, "years old" else: print "No such user" getAge("joe").addCallback(printResult)
from twisted.enterprise import adbapi # Gadfly cp = adbapi.ConnectionPool("gadfly", "test", "/tmp/gadflyDB") # PostgreSQL PyPgSQL cp = adbapi.ConnectionPool("pyPgSQL.PgSQL", database="test") # MySQL cp = adbapi.ConnectionPool("MySQLdb", db="test")
现在为止,您已经知道如何在twisted中使用数据库了。你也许需要进一步阅读 adbapi 模块的 文档以了解其它的功能和方法, 希望这篇文章给你指明了一条光明之路。