小雪崩 发表于 2017-5-3 09:08:32

python 简单的Http服务器

  代码:
'''Created on 2012-3-13@author: Administrator'''#!/usr/bin/env pythonfrom os import curdir,sepfrom BaseHTTPServer import BaseHTTPRequestHandler,HTTPServerclass 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 quityushh-PC - - code 501, message Unsupported method ('HEAD')yushh-PC - - "HEAD / HTTP/1.1" 501 -yushh-PC - - code 404, message File Not Found: /yushh-PC - - "GET / HTTP/1.1" 404 -yushh-PC - - code 404, message File Not Found: /favicon.icoyushh-PC - - "GET /favicon.ico HTTP/1.1" 404 -yushh-PC - - code 501, message Unsupported method ('HEAD')yushh-PC - - "HEAD / HTTP/1.1" 501 -yushh-PC - - code 404, message File Not Found: /favicon.icoyushh-PC - - "GET /favicon.ico HTTP/1.1" 404 -yushh-PC - - code 404, message File Not Found: /a.htmlyushh-PC - - "GET /a.html HTTP/1.1" 404 -yushh-PC - - code 404, message File Not Found: /favicon.icoyushh-PC - - "GET /favicon.ico HTTP/1.1" 404 -
页面访问:Error responseError 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返回给客户端
页: [1]
查看完整版本: python 简单的Http服务器