Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active January 31, 2017 15:35
Show Gist options
  • Save WebReflection/3c75d2495a5aa3b12f4f to your computer and use it in GitHub Desktop.
Save WebReflection/3c75d2495a5aa3b12f4f to your computer and use it in GitHub Desktop.

Basic utility to launch a python 2 or python 3 simple http server.

#!/usr/bin/env bash

if [ "$1" != "" ]; then
  PORT="$1"
elif [ "$PORT" = "" ]; then
  PORT=8000
fi

echo "http://localhost:$PORT/"

VERSION=$(python --version)
if [ "${VERSION:7:1}" = "3" ]; then
    python -m http.server $PORT
else
    python -m SimpleHTTPServer $PORT
fi

Save it in /usr/local/bin/server and chmod +x /usr/local/bin/server

@WebReflection
Copy link
Author

WebReflection commented Oct 20, 2016

With CORS enabled

#!/usr/bin/env python

try:
    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:
    from BaseHTTPServer import HTTPServer, test
    from SimpleHTTPServer import SimpleHTTPRequestHandler

class CORSRequestHandler (SimpleHTTPRequestHandler):

    def do_OPTIONS(self):
        self.send_response(200, 'OK')
        self.end_headers()

    def do_POST(self, *args, **kwargs):
        self.data_string = self.rfile.read(int(self.headers['Content-Length']))
        SimpleHTTPRequestHandler.do_GET(self)
        self.end_headers()

    def end_headers (self):
        if hasattr(self, 'data_string'):
            self.send_header('X-Posted-Data', self.data_string)
        self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-type')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Credentials', 'true')
        self.send_header('Access-Control-Allow-Origin', '*')
        SimpleHTTPRequestHandler.end_headers(self)

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

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