Python

原文地址:http://zhouzhk.iteye.com/blog/765884

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 estpyWeb

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

Html代码  收藏代码
  1. <html>  
  2. <body>  
  3.      Hello World!  
  4. </body>  
  5. </html>  

     建立另外一个文件:

Html代码  收藏代码
  1. <html>  
  2. <body>  
  3.      Test  
  4. </body>     
  5. </html>  

  3) 在新的命令行窗口执行 twistd web -n -p 8090  --path E:work estpyWeb

  4) 在浏览器访问 http://localhost:8090/;就能看到 Hello World了。http://localhost:8090/test.html就能看到Test了。

     如果没有看到,就检查自己的浏览器,是不是设置了代理服务器,而没有把localhost排除掉。

二)启动web server方法二

  1)在E:work est目录下建立文件server.py

Python代码  收藏代码
  1. from twisted.application import internet, service  
  2. from twisted.web import static, server  
  3.   
  4. resource = static.File("E:/test/pyWeb")  
  5. application = service.Application('pyWeb')  
  6. site = server.Site(resource)  
  7. sc = service.IServiceCollection(application)  
  8. tcpserver = internet.TCPServer(8090, site)  
  9. tcpserver.setServiceParent(sc)  

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

  3) 在浏览器访问 http://localhost:8090 就能看到Hello World

三) 启动web server方法三

   1)在E:work est目录下建立文件server.py

Python代码  收藏代码
  1. from twisted.internet import reactor  
  2. from twisted.web import static, server  
  3.   
  4. resource = static.File("E:/test/pyWeb")  
  5. reactor.listenTCP(8090, server.Site(resource))  
  6. reactor.run()  

 

   2) 在新的命令行窗口,cd e:work est,执行python server.py

   3) 在浏览器访问 http://localhost:8090 就能看到Hello World

   如果E:work estpyWeb还有下级目录,例如test,访问http://localhost:8090/test有什么效果呢? 你会看到这个目录下所有文件的列表。这显然不是我们想要的,那就在这个目录下放一个index.html来屏蔽,也许有其他方法,例如修改twisted.web.static.py中相应的代码。

原文地址:https://www.cnblogs.com/wangjiangze/p/3594240.html