How to run a http server which serves a specific path? How to run a http server which serves a specific path? python python

How to run a http server which serves a specific path?


In Python 3.7 SimpleHTTPRequestHandler can take a directory argument:

import http.serverimport socketserverPORT = 8000DIRECTORY = "web"class Handler(http.server.SimpleHTTPRequestHandler):    def __init__(self, *args, **kwargs):        super().__init__(*args, directory=DIRECTORY, **kwargs)with socketserver.TCPServer(("", PORT), Handler) as httpd:    print("serving at port", PORT)    httpd.serve_forever()

and from the command line:

python -m http.server --directory web

To get a little crazy... you could make handlers for arbitrary directories:

def handler_from(directory):    def _init(self, *args, **kwargs):        return http.server.SimpleHTTPRequestHandler.__init__(self, *args, directory=self.directory, **kwargs)    return type(f'HandlerFrom<{directory}>',                (http.server.SimpleHTTPRequestHandler,),                {'__init__': _init, 'directory': directory})with socketserver.TCPServer(("", PORT), handler_from("web")) as httpd:    print("serving at port", PORT)    httpd.serve_forever()


If you just want serve static file you can do it by running SimpleHTTPServer module using python 2:

 python -m SimpleHTTPServer

Or with python 3:

 python3 -m http.server

This way you do not need to write any script.


https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler

This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests.

So you just need to change the current directory prior to starting the server - see os.chdir

eg:

import http.serverimport socketserverimport osPORT = 8000web_dir = os.path.join(os.path.dirname(__file__), 'web')os.chdir(web_dir)Handler = http.server.SimpleHTTPRequestHandlerhttpd = socketserver.TCPServer(("", PORT), Handler)print("serving at port", PORT)httpd.serve_forever()