MChan MChan - 1 month ago 34
Python Question

Python - Enable access control on simple http server

I have the following shell script for very simple http server

#!/bin/sh

echo "Serving at http://localhost:3000"
python -m SimpleHTTPServer 3000


and I was wondering how I can enable /add [ Access-Control-Allow-Origin: * ] on this server?

Answer

Unfortunately, SimpleHTTPServer is really that simple that it does not allow any customization, especially not of the headers it sends. You can however create a simple HTTP server yourself, using most of SimpleHTTPServerRequestHandler, and just add that desired header.

Simply create a file simple-cors-http-server.py (or whatever) and put the following inside:

#!/usr/bin/env python2
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer

class CORSRequestHandler (SimpleHTTPRequestHandler):
    def end_headers (self):
        self.send_header('Access-Control-Allow-Origin', '*')
        SimpleHTTPRequestHandler.end_headers(self)

if __name__ == '__main__':
    BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)

Then you can do python simple-cors-http-server.py and it will launch your modified server which will set the CORS header for every response.

With the shebang at the top, make the file executable and put it into your PATH, and you can just run it using simple-cors-http-server.py too.


For a solution that works with Python 3, you could simple change the imports above to import from the http.server module (all the types are there).

Alternatively, you could use this which works on both Python 3 and Python 2. The script first tries to import from the Python 3 locations and falls back to Python 2:

#!/usr/bin/env python
try:
    # Python 3
    from http.server import HTTPServer, SimpleHTTPRequestHandler, test as test_orig
    import sys
    def test (*args):
        test_orig(*args, port=int(sys.argv[1]) if len(sys.argv) > 1 else 8000)
except ImportError: # Python 2
    from BaseHTTPServer import HTTPServer, test
    from SimpleHTTPServer import SimpleHTTPRequestHandler

class CORSRequestHandler (SimpleHTTPRequestHandler):
    def end_headers (self):
        self.send_header('Access-Control-Allow-Origin', '*')
        SimpleHTTPRequestHandler.end_headers(self)

if __name__ == '__main__':
    test(CORSRequestHandler, HTTPServer)
Comments