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

If I run 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 server requests to start with '/ public', which need to be pulled from the /protected/public directory.

for example, a request http://localhost:8000/public/index.html will serve the file in /protected/public/index.html

Is this possible with an embedded server or do I need to write a custom one?

+4
source share
3 answers

I donโ€™t think SimpleHTTPServer has this function, however, if you use a symbolic link inside / test that points to / protected / public, this should do the same effectively.

+2
source

I think I found the answer to this question, mainly due to changing the current working directory, starting the server and then returning to the original working directory.

Here is how I achieved this, I commented on two sets of options for you, since the solution for me simply moved to a folder in my application directory and then returned one level to the original application directory. But you might want to go to the whole other directory in your file system and then go back somewhere else or not.

 #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!

+8
source

I think this is absolutely possible. You can start the server inside the /test directory and override the translate_path SimpleHTTPRequestHandler method 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.

+8
source

Source: https://habr.com/ru/post/1382594/


All Articles