首页 电脑 电脑学堂 查看内容

使用Twisted实现一个简单Web服务器

2005-9-10 01:45 711 0

摘要: 我的原文发在Python版,这里也发一个,好增加点Python版的人气。希望支持。下面是原文: 作者:梅劲松 版权:本文档为MIT授权 运行环境:Python 2.3+Twisted的py-23安装版...
关键词: nbsp resource Twisted Python import Web reactor 目录 self 一个

我的原文发在Python版,这里也发一个,好增加点Python版的人气。希望支持。下面是原文: 作者:梅劲松 版权:本文档为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,看到你的站点了吗?
声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系 [邮箱地址] 删除

路过

雷人

握手

鲜花

鸡蛋

最新评论

返回顶部