TypeError:必须可以转换为缓冲区,而不是HTTPResponse

时间:2015-08-11 08:26:57

标签: 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)`

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字节的文件。 什么是正确的方法。

1 个答案:

答案 0 :(得分:5)

来自the documentation on streaming requests

  

使用requests.Response.iter_lines(),您可以轻松地进行迭代   流媒体API,如Twitter Streaming API。只需将流设置为   为True并使用iter_lines()

迭代响应

然后:

iter_lines(chunk_size=512, decode_unicode=None, delimiter=None)
     

迭代响应数据,一次一行。何时stream=True   在请求中设置,这避免了立即读取内容   对于大回应的记忆。

     

注意此方法不可重入安全。

所以你的代码可能会像:

一样使用它
with open('a.pdf', 'wb') as handle:
    handle.writelines(label.iter_lines())
相关问题