Python:从RestAPI下载zip文件

2024-06-01 03:08:41 发布

您现在位置:Python中文网/ 问答频道 /正文

第三方RestAPI提供服务器日志文件,目前我们正在使用curl命令下载日志文件,比如

curl -H "X-Auth-Token: XXXXXXXXXXXXXXXXXXXXXXXXXX" https://host_address/api/v3.0/admin/logs -o logs.zip

但我正在尝试使用Flask/Python创建简单的仪表板

下面是我的Python/Flask代码:

^{pr2}$

但是当我从浏览器中点击那个网址时,我得到了下面的错误信息

Traceback (most recent call last):
...
...
...
  File "/Users/admin/Documents/project/__init__.py", line 940, in download_console_logs
    res.content,
  File "/Users/admin/Documents/project/venv3/lib/python3.6/site-packages/requests/models.py", line 823, in content
    self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
  File "/Users/admin/Documents/project/venv3/lib/python3.6/site-packages/requests/models.py", line 745, in generate
    for chunk in self.raw.stream(chunk_size, decode_content=True):
  File "/Users/admin/Documents/project/venv3/lib/python3.6/site-packages/urllib3/response.py", line 436, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/Users/admin/Documents/project/venv3/lib/python3.6/site-packages/urllib3/response.py", line 384, in read
    data = self._fp.read(amt)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 449, in read
    n = self.readinto(b)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 497, in readinto
    self._close_conn()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 403, in _close_conn
    fp.close()
AttributeError: 'NoneType' object has no attribute 'close'

我使用PyCharm设置了断点/调试器,并且能够看到res.content中包含二进制数据,但我无法确定这里出了什么问题。在

这是一个简单的图表,它解释了我要做什么, enter image description here

更新:回答:我采用了以下方法,它以非常有效的方式解决了我的问题。在

@app.route('/download/server/logs')
def download_log():
    import requests
    from flask import Reponse
    res = requests.get('http://<rest_api_host>/v1.2/admin/logs', stream=True)
    return Response(
        res.iter_content(chunk_size=1024),
        direct_passthrough=True
    )

Tags: inpyselfprojectadminliblinesite
2条回答

如果要下载文件,请尝试烧瓶的响应方法:

import requests
from flask import Response
@app.route('/download/server/logs')
def download_log():
res = requests.get('http://<rest_api_host>/v1.2/admin/logs')
return Response(res.content,headers = dict(res.headers))

我不确定你是否给出了正确的错误信息。但是我认为如果您将一个字符串传递给send_file()方法,那么它将无法工作。您需要传递二进制数据。在

如果您将res.content包装在io.BytesIO()内并将其传递给send_file()方法,我相信它应该可以工作。在

例如:

@app.route('/download/server/logs')
def download_log():
    import requests
    from flask import send_file
    import io
    res = requests.get('http://<rest_api_host>/v1.2/admin/logs', stream=True)
    return send_file(
        io.BytesIO(res.content),
        attachment_filename='console_log.zip',
        mimetype='application/zip'
    )

希望有帮助!!在

相关问题 更多 >