代码:
'''
Created on 2012-3-13
@author: Administrator
'''
#!/usr/bin/env python
from os import curdir,sep
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
f=open(curdir+sep+self.path)
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
except IOError:
self.send_error(404, 'File Not Found: %s' % self.path)
def main():
try:
server = HTTPServer(('',80),MyHandler)
print 'welcome to the ,machine...',
print 'Press ^C once or twice to quit'
server.serve_forever()
except KeyboardInterrupt:
print '^C received,shutting down server'
server.socket.close()
if __name__=='__main__':
main()
运行:
welcome to the ,machine... Press ^C once or twice to quit
yushh-PC - - [13/Mar/2012 10:19:13] code 501, message Unsupported method ('HEAD')
yushh-PC - - [13/Mar/2012 10:19:13] "HEAD / HTTP/1.1" 501 -
yushh-PC - - [13/Mar/2012 10:19:51] code 404, message File Not Found: /
yushh-PC - - [13/Mar/2012 10:19:51] "GET / HTTP/1.1" 404 -
yushh-PC - - [13/Mar/2012 10:19:51] code 404, message File Not Found: /favicon.ico
yushh-PC - - [13/Mar/2012 10:19:51] "GET /favicon.ico HTTP/1.1" 404 -
yushh-PC - - [13/Mar/2012 10:20:08] code 501, message Unsupported method ('HEAD')
yushh-PC - - [13/Mar/2012 10:20:08] "HEAD / HTTP/1.1" 501 -
yushh-PC - - [13/Mar/2012 10:20:10] code 404, message File Not Found: /favicon.ico
yushh-PC - - [13/Mar/2012 10:20:10] "GET /favicon.ico HTTP/1.1" 404 -
yushh-PC - - [13/Mar/2012 10:20:51] code 404, message File Not Found: /a.html
yushh-PC - - [13/Mar/2012 10:20:51] "GET /a.html HTTP/1.1" 404 -
yushh-PC - - [13/Mar/2012 10:20:51] code 404, message File Not Found: /favicon.ico
yushh-PC - - [13/Mar/2012 10:20:51] "GET /favicon.ico HTTP/1.1" 404 -
页面访问:
Error response
Error code 404.
Message: File Not Found: /a.html.
Error code explanation: 404 = Nothing matches the given URI.
注意:
1、HTTPServer是基本的服务类
2、BaseHTTPServer除了0获得客户请求外不做其他事情
3、BaseHTTPResquestHandler执行标准的GET和HEAD请求并可以通过调用cgi脚本生成html返回给客户端