Reputation: 4666
I have a function which fetch a pdf file from an api connection.
My code:
label = fk.fetch_labels(oiids)
with open('a.pdf', 'wb') as handle:
cont = label.raw
print cont
handle.write(cont)`
fetch_labels :
def fetch_labels(self, orderItemIds):
headers = {'Accept': 'application/octet-stream'}
url = "https://api.flipkart.net/sellers/orders/shipments"
payload = {'orderItemIds':','.join(orderItemIds)}
return self.session.get(url, headers=headers, params=payload, stream=True)`
on running above code it throws error:
<urllib3.response.HTTPResponse object at 0x7f1d8fa24d50>
Traceback (most recent call last):
File "test.py", line 23, in <module>
handle.write(cont)
TypeError: must be convertible to a buffer, not HTTPResponse `
When i write it to a pdf file using 'wb' it just create a 0 byte file. whats the correct way.
Upvotes: 1
Views: 9261
Reputation: 10129
From the documentation on streaming requests:
With requests.Response.iter_lines() you can easily iterate over streaming APIs such as the Twitter Streaming API. Simply set stream to True and iterate over the response with iter_lines()
And thence:
iter_lines(chunk_size=512, decode_unicode=None, delimiter=None)
Iterates over the response data, one line at a time. When
stream=True
is set on the request, this avoids reading the content at once into memory for large responses.Note This method is not reentrant safe.
So your code would probably use it like:
with open('a.pdf', 'wb') as handle:
handle.writelines(label.iter_lines())
Upvotes: 5