Skip to content

Instantly share code, notes, and snippets.

@chrisbolin
Last active March 22, 2023 13:53
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save chrisbolin/2e90bc492270802d00a6 to your computer and use it in GitHub Desktop.
Save chrisbolin/2e90bc492270802d00a6 to your computer and use it in GitHub Desktop.
Python SimpleHTTPServer for Static Serving (React / Angular / Ember) in HTML5 mode (a la mod_rewrite)
'''
Taken from:
http://stackoverflow.com/users/1074592/fakerainbrigand
http://stackoverflow.com/questions/15401815/python-simplehttpserver
'''
import SimpleHTTPServer, SocketServer
import urlparse, os
PORT = 3000
INDEXFILE = 'index.html'
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
# Parse query data to find out what was requested
parsedParams = urlparse.urlparse(self.path)
# See if the file requested exists
if os.access('.' + os.sep + parsedParams.path, os.R_OK):
# File exists, serve it up
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self);
else:
# send index.html, but don't redirect
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
with open(INDEXFILE, 'r') as fin:
self.copyfile(fin, self.wfile)
Handler = MyHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
@mauronr
Copy link

mauronr commented Sep 5, 2018

Very handy. Thank you for sharing.

@phuongtailtranminh
Copy link

Very helpful for quick testing

@alexislefebvre
Copy link

Thanks, I added #!/usr/bin/env python on the first line to make it executable (it also requires chmod +x serve.py).

@faelp22
Copy link

faelp22 commented Dec 30, 2019

Thanks, will you have a version for Python 3?

@faelp22
Copy link

faelp22 commented Dec 30, 2019

I made an adjustment for Python 3, I don't know if it's very good

https://gist.github.com/faelp22/36c9bfca83780d3da73f07d66a7ec2ae

@chrisbolin
Copy link
Author

Glad you found it useful! Thanks for making the python3 version :)

@samkamin
Copy link

Just wanted to thank chrisbolin (and faelp22) for this. Gonna really help me with testing.

@chrisbolin
Copy link
Author

@samkamin you are very welcome!

@Shishiram
Copy link

Thanks, Do you know how I can fetch data or list of files being served in react?

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