this is my Python3 project hiearchy:
JavaScript
x
7
1
projet
2
3
script.py
4
web
5
6
index.html
7
From script.py
, I would like to run a http server which serve the content of the web
folder.
Here is suggested this code to run a simple http server:
JavaScript
1
9
1
import http.server
2
import socketserver
3
4
PORT = 8000
5
Handler = http.server.SimpleHTTPRequestHandler
6
httpd = socketserver.TCPServer(("", PORT), Handler)
7
print("serving at port", PORT)
8
httpd.serve_forever()
9
but this actually serve project
, not web
. How can I specify the path of the folder I want to serve?
Advertisement
Answer
In Python 3.7 SimpleHTTPRequestHandler
can take a directory
argument:
JavaScript
1
16
16
1
import http.server
2
import socketserver
3
4
PORT = 8000
5
DIRECTORY = "web"
6
7
8
class Handler(http.server.SimpleHTTPRequestHandler):
9
def __init__(self, *args, **kwargs):
10
super().__init__(*args, directory=DIRECTORY, **kwargs)
11
12
13
with socketserver.TCPServer(("", PORT), Handler) as httpd:
14
print("serving at port", PORT)
15
httpd.serve_forever()
16
and from the command line:
JavaScript
1
2
1
python -m http.server --directory web
2
To get a little crazy… you could make handlers for arbitrary directories:
JavaScript
1
12
12
1
def handler_from(directory):
2
def _init(self, *args, **kwargs):
3
return http.server.SimpleHTTPRequestHandler.__init__(self, *args, directory=self.directory, **kwargs)
4
return type(f'HandlerFrom<{directory}>',
5
(http.server.SimpleHTTPRequestHandler,),
6
{'__init__': _init, 'directory': directory})
7
8
9
with socketserver.TCPServer(("", PORT), handler_from("web")) as httpd:
10
print("serving at port", PORT)
11
httpd.serve_forever()
12