代码之家  ›  专栏  ›  技术社区  ›  Murtuza Z

Python:从RestAPI下载zip文件

  •  1
  • Murtuza Z  · 技术社区  · 6 年前

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

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

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

    下面是我的Python/Flask代码:

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

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

    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
        )
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   Roberto Caboni Prince Rabadiya    4 年前
    try:
        srcFileName="filename"
        with open(srcFileName, 'wb') as f:
            f.write(srcFileName)
    except Exception as e:
        print(e)
    
        2
  •  1
  •   Aakash Handa    4 年前

    从本地文件夹下载

    def download_Object():
        try:
            srcFileName="bulk_file.zip"
            with open(srcFileName, 'wb') as f:
                f.write(srcFileName)
        except Exception as e:
            print(e)
    
        3
  •  0
  •   Nimeshka Srimal    6 年前

    我不确定你是否给出了正确的错误信息。但是我认为如果你把一个字符串传递给 send_file()

    如果你包起来 res.content 里面 io.BytesIO() 发送文件() 方法,我相信它应该有效。

    @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'
        )
    

        4
  •  0
  •   SUBHAM MAJAVADIYA    6 年前

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

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