python web server_python超简单的web服务器

今天无意google时看见,心里突然想说,python做web服务器,用不用这么简单啊,看来是我大惊小怪了.

web1.py

#!/usr/bin/python

import SimpleHTTPServer

SimpleHTTPServer.test()

web2.py

#!/usr/bin/python

import SimpleHTTPServer

import SocketServer

import os

PORT = 80

WEBDIR = "f:/python语言学习"

class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):

def translate_path(self, path):

os.chdir(WEBDIR)

return SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self,path)

try:

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "dir %s serving at port %s"%(repr(WEBDIR), PORT)

httpd.serve_forever()

except:pass

web3.py , cgi server ,7777端口, 在web3.py执行目录下新建cgi-bin目录 , 在cgi-bin目录写hello.py

web3.py

from CGIHTTPServer import CGIHTTPRequestHandler

from BaseHTTPServer import HTTPServer

server_address=('',7777)

httpd = HTTPServer(server_address, CGIHTTPRequestHandler)

httpd.serve_forever()

hello.py

#!c:/Python24/python.exe

print "HTTP/1.0 200 OK"

print "Content-Type: text/html"

print ""

print "

"

print "Hello World!"

print ""

以下这些是需要安装了 twisted 才能使用的

web4.py

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

PORT=8888

resource = static.File('/')

resource.processors = { '.html' : ReStructured }

resource.indexNames = [ 'index.html']

reactor.listenTCP(

PORT,

server.Site( resource )

)

reactor.run( )

web5.py, 这是又是支持cgi的,又是需要twisted模块的,也是需要在cgi-bin目录下执行,上边的hello.py也能用

# -*- coding: utf-8 -*-

from twisted.internet import reactor

from twisted.web import static, server, twcgi

from twisted.web.resource import Resource

class Collection(Resource):

def render_GET(self, request):

return "hello world 你好"

root = static.File('./')

root.putChild('', Collection())

root.putChild('img', static.File('./img'))

root.putChild('cgi-bin', twcgi.CGIDirectory('cgi-bin'))

reactor.listenTCP(80, server.Site(root))

reactor.run()

当然,想实现复杂功能还是需要自己搞代码的,只不过想惊叹python的模块集成得太多功能了.

python超简单的web服务器。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值