python的twisted 學習

來源:互聯網
上載者:User

在看了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之後,馬上去查詢資料庫,效果很好。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.