今天无意google时看见,心里突然想说,python做web服务器,用不用这么简单啊,看来是我大惊小怪了.
web1.py
web1.py Python123 | #!/usr/bin/pythonimportSimpleHTTPServerSimpleHTTPServer.test() |
web2.py
123456789101112131415161718 | #!/usr/bin/pythonimportSimpleHTTPServerimportSocketServerimportos PORT= 80WEBDIR= "f:/python语言学习" classHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): deftranslate_path(self,path): os.chdir(WEBDIR) returnSimpleHTTPServer.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
web3.py Python12345 | fromCGIHTTPServer import CGIHTTPRequestHandler fromBaseHTTPServer import HTTPServer server_address=('',7777) httpd= HTTPServer(server_address,CGIHTTPRequestHandler) httpd.serve_forever() |
hello.py
hello.py Python12345678 | #!c:/Python24/python.exe print"HTTP/1.0 200 OK"print"Content-Type: text/html"print""print"<p>"print"Hello World!"print"</p>" |
以下这些是需要安装了 twisted 才能使用的
web4.py
1234567891011121314151617181920212223 | fromtwisted.web.resourceimport Resource fromtwisted.webimport server fromtwisted.webimport static fromtwisted.internetimport reactor classReStructured(Resource ): def__init__(self,filename,*a): self.rst= open(filename ).read() def render(self,request ): returnself.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也能用
web5.py Python123456789101112131415 | # -*- coding: utf-8 -*-fromtwisted.internetimport reactorfromtwisted.webimport static,server,twcgifromtwisted.web.resourceimport Resource classCollection(Resource): defrender_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服务器。