Last Updated: February 25, 2016
·
4.203K
· alettieri

Javascript MVC and python SimpleHTTPServer

I wanted a quick way to setup a way to develop a single page JS app using Backbone.js and python's SimpleHTTPServer.

I am using pushState to handle url routing and wanted pages to work if they were either re-loaded or visited directly.

Here is a little python module that should properly serve up asset files if they exist, otherwise stream down the index.html file.

import SimpleHTTPServer, SocketServer, urlparse, os

class Handler( SimpleHTTPServer.SimpleHTTPRequestHandler ):
    def do_GET( self ):
        urlParams = urlparse.urlparse(self.path)
        if os.access( '.' + os.sep + urlParams.path, os.R_OK ):
            SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self);
        else:
            self.send_response(200)
            self.send_header( 'Content-type', 'text/html' )
            self.end_headers()
            self.wfile.write( open('index.html').read() )

httpd = SocketServer.TCPServer( ('127.0.0.1', 8000), Handler )
httpd.serve_forever()

class Handler( SimpleHTTPServer.SimpleHTTPRequestHandler ):

The Handler object inherits from SimpleHTTPServer.SimpleHTTPRequestHandler

def do_GET( self ):
    urlParams = urlparse.urlparse(self.path)
    if os.access( '.' + os.sep + urlParams.path, os.R_OK ):
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self);

Here we override the doGET method. Then check to see if there is a physical file for the requested url, likely an image, js or css file. If one is found, we pass the process on to the SimpleHTTPRequestHandler.doGET method. So things behave like normal.

else:
    self.send_response(200)
    self.send_header( 'Content-type', 'text/html' )
    self.end_headers()
    self.wfile.write( open('index.html').read() )

Otherwise, we stream down the index.html file content, because this is likely an application specific route.

Here we spin up an http connection for 12.7.0.0.1 (localhost) under port 8000. So http://localhost:8000.

httpd = SocketServer.TCPServer( ('127.0.0.1', 8000), Handler )
httpd.serve_forever()

To fire things off simply save the file (something like http-server.py). Then run the following in your command line:

$: python http-server.py

You should now be able to fire up the http://localhost:8000 url in your browser and get the desired pushState behavior.

1 Response
Add your response

Thanks for this, it works great!

over 1 year ago ·