欢迎访问宙启技术站
智能推送

文件响应器的Python实现方法

发布时间:2023-12-11 01:08:20

文件响应器是一个处理HTTP请求中的文件下载的组件。它可以根据请求中的文件路径,将对应文件发送给请求方。下面是一个使用Python实现文件响应器的方法,并附带一个使用例子。

首先,我们需要导入Python的HTTP服务器相关的库:

from http.server import BaseHTTPRequestHandler, HTTPServer
import os

接下来,我们定义一个继承自BaseHTTPRequestHandler的类,并重写其do_GET方法来处理HTTP请求:

class FileRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # 获取请求的文件路径
        file_path = self.path[1:]
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'File not found')
            return
        
        # 设置响应状态
        self.send_response(200)
        
        # 根据文件扩展名设置响应的Content-Type
        file_ext = os.path.splitext(file_path)[1]
        content_type = 'application/octet-stream'  # 默认的二进制文件类型
        if file_ext == '.txt':
            content_type = 'text/plain'
        elif file_ext == '.html':
            content_type = 'text/html'
        # 其他文件类型可以自行添加
        
        # 设置响应头部
        self.send_header('Content-Type', content_type)
        self.send_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_path))
        self.send_header('Content-Length', os.path.getsize(file_path))
        self.end_headers()
        
        # 发送文件内容
        with open(file_path, 'rb') as f:
            self.wfile.write(f.read())

最后,我们创建一个HTTP服务器,并将我们定义的文件请求处理器绑定到服务器上:

def run(server_class=HTTPServer, handler_class=FileRequestHandler, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print('Starting server at http://localhost:%d' % port)
    httpd.serve_forever()


if __name__ == '__main__':
    run()

使用例子:

1. 在你的电脑上创建一个名为example.txt的文本文件,并将一些内容写入这个文件中。

2. 打开命令行终端,并进入到你的Python脚本所在的目录。

3. 运行Python脚本:python file_responder.py

4. 在浏览器中访问URL http://localhost:8000/example.txt,将会下载example.txt文件到你的电脑上。

这就是使用Python实现文件响应器的方法,并给出了一个简单的使用例子。你可以根据自己的需求和喜好对文件响应器进行定制和扩展。