how save response from flask to .zip

I'm have server on flask

@app.route('/', methods=['POST'])
def main():
    if request.method == 'POST':
        return send_from_directory(directory='./', filename='data.zip')

I send the request with

import requests
r = requests.post("http://127.0.0.1:5002", data=data)

I'm get

Response [200]

How can i save the r in data.zip on client?

1 answer

  • answered 2020-05-22 12:43 furas

    Use open(), read() and close() with byte mode wb

    import requests
    
    r = requests.post("http://127.0.0.1:5002", data=data)
    
    f = open('data.zip', 'wb')
    f.write(r.content)
    f.close()
    

    Or using with

    import requests
    
    r = requests.post("http://127.0.0.1:5002", data=data)
    
    with open('data.zip', 'wb') as f:
        f.write(r.content)
    

    If it is bigger file then you can stream data to read and save in chunks

    import requests
    
    r = requests.post("http://127.0.0.1:5002", data=data, stream=True)
    
    with open('data.zip', 'wb') as f:
         for chunk in r.iter_content(chunk_size=8192): 
             f.write(chunk)
    

    Requests doc: Streaming Requests


    BTW: similar question on Stackoverflow: Download large file in python with requests