HTTPServer-根据GET请求下载请求的文件

时间:2020-01-01 16:10:59

标签: python http

我有一个Python HTTP服务器,正在尝试从中下载文件以正常工作。例如,我在/ server目录中有HTTP服务器,并且我希望能够通过GET请求从该目录下载任何文件。因此,如果我输入http://localhost:8000/example.txt,它应该提供下载example.txt(如果存在的话)。

我将如何实现?当前的行为是,除了显示Hi以外,对任何GET请求都无效。

我的代码:

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)

谢谢

0 个答案:

没有答案