I have a Python HTTP server and I'm trying to make downloading files from it to work. For an example, I have HTTP server in a /server directory and I want to be able to download any file from that directory with a GET request. So if I type http://localhost:8000/example.txt, it should offer to download example.txt, if it exists.
How would I achieve so? The current behavior is that is does nothing with any GET request, other than show Hi.
My code:
import argparse
from http.server import HTTPServer, BaseHTTPRequestHandler
from shutil import copyfileobj
from os import path as ospath
import cgi
import cgitb; cgitb.enable(format="text")
from io import StringIO
import urllib
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def _html(self, message):
"""This just generates an HTML document that includes `message`
in the body. Override, or re-write this do do more interesting stuff.
"""
content = f"<html><body><h1>{message}</h1></body></html>"
return content.encode("utf8") # NOTE: must return a bytes object!
def do_GET(self):
self._set_headers()
self.wfile.write(self._html("hi!"))
def do_HEAD(self):
self._set_headers()
def run(server_class=HTTPServer, handler_class=S, addr="localhost", port=8000):
server_address = (addr, port)
httpd = server_class(server_address, handler_class)
print(f"Starting httpd server on {addr}:{port}")
httpd.serve_forever()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run a simple HTTP server")
parser.add_argument(
"-l",
"--listen",
default="localhost",
help="Specify the IP address on which the server listens",
)
parser.add_argument(
"-p",
"--port",
type=int,
default=8000,
help="Specify the port on which the server listens",
)
args = parser.parse_args()
run(addr=args.listen, port=args.port)
Thanks