python - TypeError : must be convertible to a buffer, 不是 HTTPResponse

标签 python python-requests

我有一个从 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/

相关文章:

python - 将 int 打包到字符串中

python - 当数字不是一个快乐的数字时何时停止

Python 请求 - 快速知道响应是否是 json 可解析的

python - 无法解码 Python Web 请求

python - 使用 python requests 提交表单并获取结果

python - pydub AudioSegment.export 正在锁定 smb 共享上的文件。无法删除该文件

python - Pandas 情节 : fixing a color by value

python - 无法使用python请求登录facebook

python - API、Python、请求未收到 POST pdf 文件

python - pickle 链接对象