Created
June 17, 2016 03:29
-
-
Save limboinf/832ba13c735c14af80dbe2ff66e44105 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
""" | |
This version responds to HTTP requests with static HTML files or | |
directory listings. | |
* Run with `python server.py .` (or some other base directory name). | |
* Point browser at `http://localhost:8080/some/path`. | |
Usage: | |
curl localhost:9000/demo.html | |
curl localhost:9000/server.py | |
... | |
:copyright: (c) 2015 by fangpeng. | |
:license: MIT, see LICENSE for more details. | |
""" | |
__date__ = '16/6/17' | |
import os, BaseHTTPServer | |
class ServerException(Exception): | |
pass | |
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): | |
""" | |
If the requested path maps to a file, that file is served. | |
If anything goes wrong, an error page is constructed. | |
""" | |
Error_Page = """\ | |
<html> | |
<body> | |
<h1>Error Accessing {path} </h1> | |
<p>{msg}</p> | |
</body> | |
</html> | |
""" | |
def do_GET(self): | |
try: | |
full_path = os.getcwd() + self.path | |
if not os.path.exists(full_path): | |
raise ServerException("'{0}' not found".format(self.path)) | |
elif os.path.isfile(full_path): | |
self.handle_file(full_path) | |
else: | |
raise ServerException("Unknown object '{0}'".format(self.path)) | |
except Exception as msg: | |
self.handle_error(msg) | |
def handle_error(self, msg, status_code=500): | |
content = self.Error_Page.format(path=self.path, msg=msg) | |
self.send_content(content, status_code) | |
def handle_file(self, path): | |
try: | |
with open(path, 'rb') as f: | |
content = f.read() | |
self.send_content(content) | |
except IOError as msg: | |
msg = "'{0}' cannot be read: {1}".format(self.path, msg) | |
self.handle_error(msg) | |
def send_content(self, content, status_code=200): | |
self.send_response(status_code) | |
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__': | |
server_addr = ('', 9000) | |
server = BaseHTTPServer.HTTPServer(server_addr, RequestHandler) | |
server.serve_forever() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment