[Turn] Python implements a simple web server

 
 
Link: https://www.shiyanlou.com/courses/552

#
-*- coding:utf-8 -*- import sys, os, BaseHTTPServer, subprocess #------------------------------------------------------------------------------- class ServerException(Exception): ''' Server internal error ''' pass #------------------------------------------------------------------------------- class base_case(object): ''' Condition processing base class ''' def handle_file(self, handler, full_path): try: with open(full_path, 'rb') as reader: content = reader.read() handler.send_content(content) except IOError as msg: msg = "'{0}' cannot be read: {1}".format(full_path, msg) handler.handle_error(msg) def index_path(self, handler): return os.path.join(handler.full_path, 'index.html') def test(self, handler): assert False, 'Not implemented.' def act(self, handler): assert False, 'Not implemented.' #------------------------------------------------------------------------------- class case_no_file(base_case): ''' file or directory does not exist ''' def test(self, handler): return not os.path.exists(handler.full_path) def act(self, handler): raise ServerException("'{0}' not found".format(handler.path)) #------------------------------------------------------------------------------- class case_cgi_file(base_case): ''' executable script ''' def run_cgi(self, handler): data = subprocess.check_output(["python", handler.full_path]) handler.send_content(data) def test(self, handler): return os.path.isfile(handler.full_path) and \ handler.full_path.endswith('.py') def act(self, handler): self.run_cgi(handler) #------------------------------------------------------------------------------- class case_existing_file(base_case): ''' if the file exists ''' def test(self, handler): return os.path.isfile(handler.full_path) def act(self, handler): self.handle_file(handler, handler.full_path) #------------------------------------------------------------------------------- class case_directory_index_file(base_case): ''' Return to the homepage file in the root path ''' def test(self, handler): return os.path.isdir(handler.full_path) and \ os.path.isfile(self.index_path(handler)) def act(self, handler): self.handle_file(handler, self.index_path(handler)) #------------------------------------------------------------------------------- class case_always_fail(base_case): ''' default processing ''' def test(self, handler): return True def act(self, handler): raise ServerException("Unknown object '{0}'".format(handler.path)) #------------------------------------------------------------------------------- class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): ''' If the request path is legal, it will return the corresponding processing Otherwise return an error page ''' Cases = [case_no_file(), case_cgi_file(), case_existing_file(), case_directory_index_file(), case_always_fail()] #Error page template Error_Page = """ \ <html> <body> <h1>Error accessing {path}</h1> <p>{msg}</p> </body> </html> """ def do_GET(self): try: #Get the full request path self.full_path = os.getcwd() + self.path # Loop through all cases and handle for case in self.Cases: if case.test(self): case.act(self) break #Handle exception except Exception as msg: self.handle_error(msg) def handle_error(self, msg): content = self.Error_Page.format(path=self.path, msg=msg) self.send_content(content, 404) #Send data to the client def send_content(self, content, status=200 ): self.send_response(status) self.send_header("Content-type", "text/html") self.send_header("Content-Length", str(len(content))) self.end_headers() self.wfile.write(content) #------------------------------------------------------------------------------- if __name__ == '__main__': serverAddress = ('', 8080) server = BaseHTTPServer.HTTPServer(serverAddress, RequestHandler) server.serve_forever()

 

plain.html

<html>
<head>
<title>Plain Page</title>
</head>
<body>
<h1>Plain Page</h1>
<p>Nothin' but HTML.</p>
</body>
</html>

 

index.html

<html>
<head>
<title>Index Page</title>
</head>
<body>
<h1>Index Page</h1>
<p>Welcome to my home.</p>
</body>
</html>

 

showtime.py

from datetime import datetime
print '''\
<html>
<body>
<p>Generated {0}</p>
</body>
</html>'''.format(datetime.now())

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325027666&siteId=291194637