Last active
February 16, 2018 21:36
-
-
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.
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
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