Search code examples
pythonflaskresponseflask-restfulsendfile

Python Flask : Returned file is not readable


While implementing a rest API in python flask, I have used several options to return a file (any type) , read it and save it to local repository of request but encountered with multiple errors as below:

Case 1:

def download_file(): return send_file('any_file.pdf') r = requests.get(url = 'http://localhost:5000/download').read()

has responded with a error Response object has no attribute read/text/content

Case 2:

def download_file(): file = open('any_file.pdf','r').read() return file r = requests.get(url = 'http://localhost:5000/download')

has responded with a error Return doesn't accept this

So How can I do this as flask is not allowing to return a file without response object and response object is not readable and doesn't support to save that file directly.


Solution

  • The Flask server code in Case 1 is correct. A more complete example:

    @app.route('/download')
    def download_file():
        # Some logic here
        send_file('any_file.pdf')
    

    However the Response object returned by requests.get doesn't have a read method. The correct way is to use:

    Response.content: Content of the response, in bytes.

    So, the client code should be:

    r = requests.get('http://localhost:5000/download')
    bytes = r.content
    
    # Now do something with bytes, for example save it:
    
    with open('downloaded_file.ext', 'wb') as f:
        f.write(bytes)