---
title: "Python - twisted web 入门学习之一"
author: "zhouzhk"
date: "2010-09-17T15:34:52Z"
tags: ["Flex", "HTML", "Python", "Web", "浏览器"]
categories: ["编程语言"]
slug: "python-twisted-web"
draft: false
lastmod: "2010-09-23T10:14:08Z"
id: 765884
url: "https://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\\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中相应的代码。