Skip to content

Instantly share code, notes, and snippets.

@cdwfs
Last active February 16, 2018 21:36
Show Gist options
  • Save cdwfs/6236990 to your computer and use it in GitHub Desktop.
Save cdwfs/6236990 to your computer and use it in GitHub Desktop.
Python script to run an HTTP server that only accepts connections from localhost. Primarily intended as a workaround for cross-origin requests preventing you from loading local assets in your local JS scripts.
import argparse
import os
import os.path
import sys
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--port", type=int, help="Port to open for HTTP connections", default=80)
parser.add_argument("-d", "--dir", help="Root directory to serve", default=".")
args = parser.parse_args()
if sys.version_info.major == 3:
import http.server
import socketserver
server_base_class = socketserver.TCPServer
class LocalTCPServer(socketserver.TCPServer):
"Only accepts requests from 127.0.0.1"
def verify_request(self, request, client_address):
return (client_address[0] == '127.0.0.1')
handler = http.server.SimpleHTTPRequestHandler
elif sys.version_info.major == 2:
import SimpleHTTPServer
import SocketServer
class LocalTCPServer(SocketServer.TCPServer):
"Only accepts requests from 127.0.0.1"
def verify_request(self, request, client_address):
return (client_address[0] == '127.0.0.1')
handler = SimpleHTTPServer.SimpleHTTPRequestHandler
root_dir = os.path.abspath(args.dir)
os.chdir(root_dir)
httpd = LocalTCPServer(("",args.port), handler)
if args.port == 80:
server_string = "localhost"
else:
server_string = "localhost:%d" % args.port
print("Serving %s at http://%s\n" % (root_dir, server_string))
httpd.serve_forever()
# Put the following into http_server.bat in the same directory,
# and put both files in your %PATH% somewhere.
'''
@echo off
python %~dp0\http_server.py %*
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment