python是一门有趣的语言,当然也可以做一些有趣的东西.
先看看这个最简单的web服务器.
import SimpleHTTPServer
SimpleHTTPServer.test()
|
当然,这个server只能在localhost下面运行.但是却可以提供静态页面显示.
再看一个稍微复杂的.
import SimpleHTTPServer
import SocketServer
PORT = 8800
handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("192.168.1.103",PORT),handler)
print 'serving at port',PORT
httpd.serve_forever()
|
上例,先创建了个tcp的server,不过,采用simple http request handler作为其handler.这样一来,你可以用网内的机子来访问这个web server了.有一点要注意,就是你的html文件目录和当前的脚本所在目录是一致的.
再往后看:
import SimpleHTTPServer
import SocketServer
import os
PORT = 8800
WEBDIR = "/www"
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def translate_path(self,path):
os.chdir(WEBDIR)
return SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self,path)
try:
#handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("192.168.1.103",PORT),Handler)
print 'dir %s serving at port %s' % (repr(WEBDIR),PORT)
httpd.serve_forever()
except:
pass
|
这个例子较上例是,可以设定html所在的目录.
如果不想用socketServer,可以直接用BaseHttpServer,他继承自SocketServer.
import BaseHTTPServer
import SimpleHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer
def run(server_class = BaseHTTPServer.HTTPServer,
handler_class = SimpleHTTPRequestHandler):
server_address = ('',8000)
httpd = server_class(server_address,handler_class)
httpd.serve_forever()
if __name__ == "__main__":
run()
|