我有一个从 api 连接获取 pdf 文件的函数。
我的代码:
label = fk.fetch_labels(oiids)
with open('a.pdf', 'wb') as handle:
cont = label.raw
print cont
handle.write(cont)`
获取标签:
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)`
运行上面的代码会抛出错误:
<urllib3.response.HTTPResponse object at 0x7f1d8fa24d50>
Traceback (most recent call last):
File "test.py", line 23, in <module>
handle.write(cont)
TypeError:必须可转换为缓冲区,而不是 HTTPResponse `
当我使用“wb”将其写入 pdf 文件时,它只会创建一个 0 字节文件。 什么是正确的方法。
最佳答案
来自 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()
然后:
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.
因此您的代码可能会像这样使用它:
with open('a.pdf', 'wb') as handle:
handle.writelines(label.iter_lines())
关于python - TypeError : must be convertible to a buffer, 不是 HTTPResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31936759/