scate636
scate636

Reputation: 135

Download content-disposition from http response header (Python 3)

Im looking for a little help here. I've been using requests in Python to gain access to a website. Im able access the website and get a response header but im not exactly sure how to download the zip file contained in the Content-disposition. Im guessing this isnt a function Requests can handle or at least I cant seem to find any info on it. How do I gain access to the file and save it?

'Content-disposition': 'attachment;filename=MT0376_DealerPrice.zip'

Upvotes: 3

Views: 6919

Answers (2)

Mickaël Le Baillif
Mickaël Le Baillif

Reputation: 2156

Using urllib instead of requests because it's a lighter library :

import urllib

req = urllib.request.Request(url, method='HEAD')
r = urllib.request.urlopen(req)
print(r.info().get_filename())

Example :

In[1]: urllib.request.urlopen(urllib.request.Request('https://httpbin.org/response-headers?content-disposition=%20attachment%3Bfilename%3D%22example.csv%22', method='HEAD')).info().get_filename()
Out[1]: 'example.csv'

Upvotes: 3

J91321
J91321

Reputation: 727

What you want to do is to access response.content. You may want to add better checks if the content really contains the file.

Little example snippet

response = requests.post(url, files={'name': 'filename.bin'}, timeout=60, stream=True)
if response.status_code == 200:
    if response.headers.get('Content-Disposition'):
        print("Got file in response")
        print("Writing file to filename.bin")
        open("filename.bin", 'wb').write(response.content)

Upvotes: 2

Related Questions