Python - twisted web 入門學習之一

python的twisted框架中帶了一個web server: twisted web。現在看看怎麼用。

 

一)準備工作

   1)到 ActiveState網站下載ActivePython2.6.xxx,我用的windows版本,然後雙擊安裝。選擇ActivePython因爲python網站上下載不了2.6.6了,奇怪;另外不用找easy_install這個python的包管理工具了。

   2)安裝相關包。打開一個命令行窗口,

       執行 easy_install twisted,會自動安裝twisted合適的版本;

       執行 easy_install zope.interface,會安裝twisted依賴的zope.interface包(?前面沒有自動安裝依賴包);

       執行 easy_install pyamf,會安裝twisted web和flex通訊用到的pyAMF包

     這些安裝過程修改了%PATH%環境變量。因此,關閉這個窗口,重新打開一個命令行窗口。

二)啓動web server方法一

  1) 建立目錄 E:\work\test\pyWeb

  2) 在目錄下建立文件 index.html:

 

<html>
<body>
	 Hello World!
</body>
</html>

     建立另外一個文件:

 

<html>
<body>
	 Test
</body>	
</html>

  3) 在新的命令行窗口執行 twistd web -n -p 8090  --path E:\work\test\pyWeb

  4) 在瀏覽器訪問 http://localhost:8090/;就能看到 Hello World了。http://localhost:8090/test.html就能看到Test了。

     如果沒有看到,就檢查自己的瀏覽器,是不是設置了代理服務器,而沒有把localhost排除掉。

二)啓動web server方法二

  1)在E:\work\test目錄下建立文件server.py

 

from twisted.application import internet, service
from twisted.web import static, server

resource = static.File("E:/test/pyWeb")
application = service.Application('pyWeb')
site = server.Site(resource)
sc = service.IServiceCollection(application)
tcpserver = internet.TCPServer(8090, site)
tcpserver.setServiceParent(sc)

  2) 在新的命令行窗口,cd e:\work\test,執行 twistd -ny server.py

  3) 在瀏覽器訪問 http://localhost:8090 就能看到Hello World

 

三) 啓動web server方法三

   1)在E:\work\test目錄下建立文件server.py

 

from twisted.internet import reactor
from twisted.web import static, server

resource = static.File("E:/test/pyWeb")
reactor.listenTCP(8090, server.Site(resource))
reactor.run()
 

   2) 在新的命令行窗口,cd e:\work\test,執行python server.py

   3) 在瀏覽器訪問 http://localhost:8090 就能看到Hello World

 

   如果E:\work\test\pyWeb還有下級目錄,例如test,訪問http://localhost:8090/test有什麼效果呢? 你會看到這個目錄下所有文件的列表。這顯然不是我們想要的,那就在這個目錄下放一個index.html來屏蔽,也許有其他方法,例如修改twisted.web.static.py中相應的代碼。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章