如何从url压缩文件,然后返回zip文件作为烧瓶中的响应[关闭]

问题描述 投票:0回答:1
def generate_files_link():
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    z=zipfile.ZipFile(io.BytesIO(r.content))

    return  Response(
            z,
            mimetype='application/zip',
            headers={'Content-Disposition':'attachment;filename=files.zip'}
            )
 

输出

raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file
python flask python-requests zip
1个回答
1
投票

您需要从 zipfile 模块中调用

ZipFile.writestr()
方法(如此处所述)将字符串转换为 zip 文件。

def generate_files_link():
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    print(r.content)
    z = zipfile.ZipFile.writestr(
        zinfo_or_arcname="files.zip", data=io.BytesIO(r.content))
    return Response(z, mimetype='application/zip', headers={'Content-Disposition': 'attachment;filename=files.zip'})
© www.soinside.com 2019 - 2024. All rights reserved.