【问题标题】:Serve a file from Python's http.server - correct response with a file从 Python 的 http.server 提供文件 - 正确响应文件
【发布时间】:2018-02-16 17:22:03
【问题描述】:

我只是想从 http.server 提供一个 PDF 文件。这是我的代码:

from http.server import BaseHTTPRequestHandler, HTTPServer

class MyServer(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/pdf')
        self.send_header('Content-Disposition', 'attachment; filename="file.pdf"')
        self.end_headers()

        # not sure about this part below
        self.wfile.write(open('/filepath/file.pdf', 'rb'))


myServer = HTTPServer(('localhost', 8080), MyServer)
myServer.serve_forever()
myServer.server_close()

我不确定我现在如何回复file.pdf,而且我一无所获。我相信标题是正确的,但我无法发送实际文件。

【问题讨论】:

    标签: python-3.x servlets httpserver simplehttpserver basehttpserver


    【解决方案1】:

    看起来您按照您的说法正确设置了标题。我已经完成了您尝试仅使用文本数据 (CSV) 执行的操作。如图所示,您的代码的一个问题是您正在尝试写入文件对象而不是实际数据。您需要执行read 才能真正获取二进制数据。

    def do_GET(self):
    
        # Your header stuff here...
    
        # Open the file
        with open('/filepath/file.pdf', 'rb') as file: 
            self.wfile.write(file.read()) # Read the file and send the contents 
    

    希望这至少能让你更接近一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-07
      • 2011-02-06
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      • 2011-02-02
      相关资源
      最近更新 更多