TypeError: must be convertible to a buffer, not HTTPResponse

TypeError: must be convertible to a buffer, not HTTPResponse

我有一个从 api 连接获取 pdf 文件的功能。

我的代码:

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)`

在 运行 上面的代码中抛出错误:

<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())