Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve directory in Python 3

I've got this basic python3 server but can't figure out how to serve a directory.

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            print(self.path)
            if self.path == '/up':
                self.send_response(200)
                self.end_headers()
                self.wfile.write(b'Going Up')
            if self.path == '/down':
                self.send_response(200)
                self.end_headers()
                self.wfile.write(B'Going Down')

httpd = socketserver.TCPServer(("", PORT), SimpleHTTPRequestHandler)
print("Server started on ", PORT)
httpd.serve_forever()

If Instead of the custom class above, I simply pass Handler = http.server.SimpleHTTPRequestHandler into TCPServer():, the default functionality is to serve a directory, but I want to serve that directory and have functionality on my two GETs above.

As an example, if someone were to go to localhost:8080/index.html, I'd want that file to be served to them

like image 264
Wayneio Avatar asked Dec 10 '22 03:12

Wayneio


1 Answers

if you are using 3.7, you can simply serve up a directory where your html files, eg. index.html is still

python -m http.server 8080 --bind 127.0.0.1 --directory /path/to/dir

for the docs

like image 182
eddyizm Avatar answered Dec 12 '22 17:12

eddyizm