歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux綜合 >> Linux資訊 >> 更多Linux >> 使用Twisted實現一個簡單Web服務器

使用Twisted實現一個簡單Web服務器

日期:2017/2/27 9:27:52   编辑:更多Linux
  自己實現Web服務器的優點就不用說太多了,主要是能控制具體的實現。也能按照自己的習慣實現互動方式。    而Twisted在tcp以下是C寫的,ip和udp部分應該是C和Python的混合產物,而http smtp等則是Python的,自己能很好的擴充。    下面來看個具體的例子:    首先你需要編輯一個Html為結尾的文件名放到你的htm目錄下。    然後在htm的上一級目錄建立一個文件,文件名為web.py,內容如下:    代碼:  [code:1:79fbd7e444]  PORT = 80#這個是80,如果你的端口被占用了,換成其他的    from twisted.web.resource import Resource  from twisted.web import server  from twisted.web import static  from twisted.internet import reactor    class ReStrUCtured( Resource ):  def __init__( self, filename, *a ):  self.rst = open( filename ).read( )    def render( self, request ):  return self.rst    resource = static.File('./htm/')  resource.processors = { '.html' : ReStructured }  resource.indexNames = [ 'index.html']    reactor.listenTCP(  PORT,  server.Site( resource )  )  reactor.run( )    [/code:1:79fbd7e444]  在控制台下進入目錄輸入 python web.py,然後打開浏覽器,輸入http://127.0.0.1,看到你的站點了嗎?




Copyright © Linux教程網 All Rights Reserved