在看了twisted的reactor模式之後,結合WEB Service 和 DBConnection Pool 做了一下的例子
from twisted.web import server, resource,http
from twisted.internet import reactor
from twisted.enterprise import adbapi
import os
class dataprocess:
def __init__(self):
self.dbpool=adbapi.ConnectionPool("MySQLdb",db="test", user="root",passwd="111111")
def getAge(self,user):
print "getAge"
return self.dbpool.runQuery("SELECT age FROM users WHERE name = 'joe'")
def printResult(self,l):
print "print Result"
if l:
print l[0][0], "years old"
else:
print "No such user"
def errorHandler(self,error):
# this isn't a very effective handling of the error, we just print it out:
print "An error has occurred: <%s>" % str(error)
class Simple(resource.Resource):
isLeaf = True
# allowedMethods = ('GET',)
def __init__(self):
pass
def render_GET(self, request):
# headers = request.getAllHeaders()
uri = request.uri
print uri
print request.args,"/n",request.path
mysqldata = dataprocess()
d = mysqldata.getAge("joe")
d.addCallback(mysqldata.printResult)
d.addErrback(mysqldata.errorHandler)
# request.setResponseCode(http.NOT_FOUND)
# return ""
# request._sendError(404,'cann not found')
return "<html>Hello, world! /n you succeed</html>"
# equivalent of cursor.execute(statement), return cursor.fetchall():
if __name__=='__main__':
site = server.Site(Simple())
reactor.listenTCP(8000, site)
print "run"
reactor.run()
該例子是一個server程式,用戶端的測試需要http://localhost:8000,伺服器端在收到Get之後,馬上去查詢資料庫,效果很好。