Reputation: 8891
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?
Upvotes: 12
Views: 12782
Reputation: 3672
I think I have found the answer to this, basically it involves changing the current working directory, starting the server and then returning back to your original working directory.
This is how I achieved it, I've commented out two sets of options for you, as the solution for me was just moving to a folder within my app directory and then back up one level to the original app directory. But, you might want to go to an entire other directory in your file system and then return someplace else or not at all.
#Setup file server
import SimpleHTTPServer
import SocketServer
import os
PORT = 5002
# -- OPTION 1 --
#os.chdir(os.path.join(os.path.abspath(os.curdir),'PATH_TO_FOLDER_IN_APP_DIR'))
# -- OPTION 2 --
#os.chdir('PATH_TO_ROOT_DIRECTORY')
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
# -- OPTION 1 --
#os.chdir(os.path.abspath('..'))
# -- OPTION 2 --
#os.chdir('PATH_TO_ORIGINAL_WORKING_DIR')
Let me know how it works out!
Upvotes: 7
Reputation: 1178
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.
Upvotes: 17
Reputation: 701
I do not believe SimpleHTTPServer has this feature, however if you use a symbolic link inside of /test that points to /protected/public, that should effectively do the same thing.
Upvotes: 5