python-3.xservletshttpserversimplehttpserverbasehttpserver

Serve a file from Python's http.server - correct response with a file


I am simply trying to serve a PDF file from the http.server. Here is my code:

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()

I am not sure how I could respond with file.pdf now and I am not getting anywhere. I am confident that the headers are correct but I cant manage to send the actual file over.


Solution

  • Looks like you are setting up the headers correctly as you say. I've done what you are trying to do only with textual data (CSV). One problem with your code as shown is that you are trying to write the file object and not the actual data. You need to do a read to actually get the binary data.

    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 
    

    Hopefully this at least gets you a bit closer.