Is it possible to have SimpleHTTPServer serve files from two different directories?

aw crud picture aw crud · Nov 22, 2011 · Viewed 11k times · Source

If I do python -m SimpleHTTPServer it serves the files in the current directory.

My directory structure looks like this:

/protected/public
/protected/private
/test

I want to start the server in my /test directory and I want it to serve files in the /test directory. But I want all requests to the server starting with '/public' to be pulled from the /protected/public directory.

e.g.a request to http://localhost:8000/public/index.html would serve the file at /protected/public/index.html

Is this possible with the built in server or will I have to write a custom one?

Answer

Prashant Borde picture Prashant Borde · Dec 5, 2013

I think it is absolutely possible to do that. You can start the server inside /test directory and override translate_path method of SimpleHTTPRequestHandler as follows:

import BaseHTTPServer
import SimpleHTTPServer
server_address = ("", 8888)
PUBLIC_RESOURCE_PREFIX = '/public'
PUBLIC_DIRECTORY = '/path/to/protected/public'

class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def translate_path(self, path):
        if self.path.startswith(PUBLIC_RESOURCE_PREFIX):
            if self.path == PUBLIC_RESOURCE_PREFIX or self.path == PUBLIC_RESOURCE_PREFIX + '/':
                return PUBLIC_DIRECTORY + '/index.html'
            else:
                return PUBLIC_DIRECTORY + path[len(PUBLIC_RESOURCE_PREFIX):]
        else:
            return SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self, path)

httpd = BaseHTTPServer.HTTPServer(server_address, MyRequestHandler)
httpd.serve_forever()

Hope this helps.