今天無心google時看見,內心忽然想說,python作web服務器,用不用這麼簡單啊,看來是我大驚小怪了.html
web1.pypython
1
2
3
|
#!/usr/bin/python
import SimpleHTTPServer
SimpleHTTPServer.test()
|
web2.pyreact
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#!/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.pyweb
web3.py服務器
1
2
3
4
5
|
from CGIHTTPServer import CGIHTTPRequestHandler
from BaseHTTPServer import HTTPServer
server_address=('',7777)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()
|
hello.py學習
1
2
3
4
5
6
7
8
|
#!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.pygoogle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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也能用spa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# -*- 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服務器。code