Created
August 8, 2021 08:10
-
-
Save xchellx/c2abcc963bbc5b82f5fb04d478cdd3a4 to your computer and use it in GitHub Desktop.
Python CORS HTTP localhost web dev server script (includes logging to file)
This file contains 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
#!/user/bin/env python3 | |
# encoding: utf-8 | |
"""Use instead of `python3 -http.server 8000` when you need CORS""" | |
from sys import stdout | |
from datetime import datetime | |
from http.server import HTTPServer, SimpleHTTPRequestHandler | |
from atexit import register as atexit | |
# For logging (to both console and file) | |
global log | |
log = open('serve' + datetime.now().strftime('%Y%m%d') + '.log', 'w') | |
def onexit(): | |
log.close() | |
atexit(onexit) | |
# For HTTPServer | |
class CORSRequestHandler(SimpleHTTPRequestHandler): | |
def end_headers(self): | |
self.send_response(200, "ok") | |
self.send_header('Access-Control-Allow-Credentials', 'true') | |
self.send_header('Access-Control-Allow-Origin', '*') | |
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') | |
self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type') | |
self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate') | |
return super(CORSRequestHandler, self).end_headers() | |
def do_OPTIONS(self): | |
self.send_response(200, "ok") | |
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('Cache-Control', 'no-store, no-cache, must-revalidate') | |
return super(CORSRequestHandler, self).end_headers() | |
def log_request(self, code='-', size='-'): | |
self.log_message('"%s" %s %s', | |
self.requestline, str(code), str(size)) | |
def log_error(self, format, *args): | |
self.log_message(format, *args) | |
def log_message(self, format, *args): | |
msg = ("%s - - [%s] %s\n" % | |
(self.address_string(), | |
self.log_date_time_string(), | |
format%args)) | |
stdout.write(msg) | |
log.write(msg) | |
log.flush() | |
# Host address to listen on (HOST:PORT) | |
HOST = "localhost" | |
# Port to listen on (HOST:PORT) | |
PORT = 8000 | |
print("HTTPServer started on " + str(HOST) + " at port " + str(PORT)) | |
print("To change the port, modify the PORT variable in this script then close and restart this script.") | |
# Start server | |
httpd = HTTPServer((HOST, PORT), CORSRequestHandler) | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment