Skip to content

Instantly share code, notes, and snippets.

@willnix
Last active May 17, 2019 11:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willnix/daed2b57ab8d613f6bfa53c6d0b46fd3 to your computer and use it in GitHub Desktop.
Save willnix/daed2b57ab8d613f6bfa53c6d0b46fd3 to your computer and use it in GitHub Desktop.
Slightly customized Python 3 HTTP Server
#!/usr/bin/env python3
from http.server import SimpleHTTPRequestHandler, HTTPServer
class CustomHTTPRequestHandler(SimpleHTTPRequestHandler):
def do_GET(self):
'''
Print request and call SimpleHTTPRequestHandler.do_GET()
to serve static files
'''
print(">"+"-"*40+"<")
print(self.requestline)
print(self.headers)
return super().do_GET()
def do_POST(self):
'''
Print request and respond with empty HTTP 200
'''
print(">"+"-"*40+"<")
print(self.requestline)
print(self.headers)
content_length = self.headers.get('Content-Length')
length = int(content_length) if content_length else 0
content_encoding = self.headers.get('Content-Encoding')
encoding = content_encoding if content_encoding else 'utf-8'
print(str(self.rfile.read(length),encoding))
self.send_response(200)
self.end_headers()
def do_HEAD(self):
self.do_GET()
# behaves like do_GET but ommits actual file contents
return super().do_HEAD()
def do_OPTIONS(self):
self.send_response(200, "ok")
self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, HEAD, OPTIONS')
self.end_headers()
do_PUT = do_POST
do_DELETE = do_GET
def end_headers(self):
'''
Add custom headers
'''
# CORS
self.send_header('Access-Control-Allow-Credentials', 'true')
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Headers", "X-Requested-With, Content-type")
#self.send_header("Content-Disposition", "attachment;filename=\"filename.jpg\"")
return super().end_headers()
if __name__ == '__main__':
bind_address = ('localhost', 8080)
httpd = HTTPServer(bind_address, CustomHTTPRequestHandler)
httpd.serve_forever()
@willnix
Copy link
Author

willnix commented May 17, 2019

This Server prints all requests to stdout, serves static files from its current working directory and adds custom headers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment