作者:梅劲松
版权:本文档为MIT授权
运行环境:Python 2.3+Twisted的py-23安装版本
自己实现Web服务器的优点就不用说太多了,主要是能控制具体的实现。也能按照自己的习惯实现互动方式。
而Twisted在tcp以下是C写的,ip和udp部分应该是C和Python的混合产物,而http smtp等则是Python的,自己能很好的扩充。
下面来看个具体的例子:
首先你需要编辑一个html为结尾的文件名放到你的htm目录下。
然后在htm的上一级目录建立一个文件,文件名为web.py,内容如下:
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( )
在控制台下进入目录输入 python web.py,然后打开浏览器,输入http://127.0.0.1,看到你的站点了吗?
xiaohu0 回复于:2005-09-08 09:36:03
支持下!
qiweixue 回复于:2005-09-08 09:38:28
支持哈...老大...
牛x...
wolfg 回复于:2005-09-08 11:06:36
支持!
Twisted还没接触过啊
Python标准库里的SimpleHTTPServer和CGIHTTPServer可以实现简单的web server
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/365606
正在学习[url=http://www.cherrypy.org/]CherryPy(a pythonic, object-oriented web development framework),也是个现成的web server,呵呵
xichen 回复于:2005-09-08 14:34:01
因为项目中其他都是twisted写的,所以用这个了。
你觉得你使用的web server有什么优点,能介绍一下吗?
wolfg 回复于:2005-09-08 14:37:57
引用:原帖由 "xichen" 发表: 因为项目中其他都是twisted写的,所以用这个了。
你觉得你使用的web server有什么优点,能介绍一下吗?
我也是刚开始学习CherryPy,准备这几天写一个小的应用。现在看了它网站上的tutorial和一些例子。等有些心得了,我写下来与大家交流。
http://www.cherrypy.org/
hspgj 回复于:2005-11-11 14:55:26
D:pywebserver>python web.py sys:1: DeprecationWarning: Non-ASCII character 'xd5' in file web.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details Traceback (most recent call last): File "web.py", line 4, in ? from twisted.web.resource import Resource ImportError: No module named twisted.web.resource
|