请求多个文件的原型。
这个是最草的情况,就是硬编码到内存中的字符串,
真实的应用还是会转到其它端口处理,或是读到硬盘上的文件吧。
#!/usr/bin/env python from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler import time starttime = time.time() class RequestHandler(BaseHTTPRequestHandler): """Definintion of the request hadnler.""" def _writeheaders(self, doc): """Write the HTTP headers for the document. If there is no documnet, send a 404 error code;""" if doc is None: self.send_response(404) else: self.send_response(200) #Always server up HTML for now. self.send_header(‘Content-type‘, ‘text/html‘) self.end_headers() def _getdoc(self, filename): """Handle a request for a document """ global starttime if filename == ‘/‘: return """ <HTML><HEAD><TITLE>sample python page</TITLE></HEAD> <BODY> THIS IS A SAMPLE PAGE. </BODY></HTML> """ elif filename == ‘/stats.html‘: return """ <HTML><HEAD><TITLE>Status</TITLE></HEAD> <BODY> This server has veen running for %d seconds. </BODY></HTML> """ % int(time.time() - starttime) else: return None def do_HEAD(self): """Handle a request for headers only""" doc = self._getdoc(self.path) self._writeheaders(doc) def do_GET(self): """Handle a request for headers and body""" doc = self._getdoc(self.path) self._writeheaders(doc) if doc is None: self.wfile.write(""" <HTML><HEAD><TITLE>Not found</TITLE></HEAD> <BODY> The requested document ‘%s‘ was not found. </BODY></HTML>""" % self.path) else: self.wfile.write(doc) serveraddr = (‘‘,8765) srvr = HTTPServer(serveraddr, RequestHandler) srvr.serve_forever()
时间: 2024-10-31 17:50:26