压缩一个文件夹,但将其存储在一个变量中?

2024-09-30 14:25:42 发布

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

我有一段代码,在临时目录中的for循环中创建文件

然而,我的目标是压缩它们,但是我不想将压缩后的文件存储在磁盘上,而是将其存储在变量中。这是我的代码:https://pastebin.com/ZTbghf8S

此代码将位于一个类中,我将从Flask web服务器将其提供给用户,如下所示:

@app.route("/download_file")
def downloadfile():
    Object = MyClass(variable='random_variable')
    return Response(Object.getFile()['object'])

我该怎么做


Tags: 文件代码https服务器目录comwebflask
1条回答
网友
1楼 · 发布于 2024-09-30 14:25:42

我之前回答过一个问题,想做一些类似的事情,尽管它似乎已经被删除了。我提出了这个gist,主题是压缩PIL图像,但概念类似

其目的是在内存中构建一个ZIP文件,并使用Flask提供服务,而无需将其写入服务器上的光盘

为了使其适应您的代码,您可以创建一个处理ans并返回元组的函数,其中第一项是输出路径,第二项是BytesIO对象

import io, os

def process_individual(ans):
        codepath = ans.find("a", {"class": "panel-group-toggle"}).text.strip().split("/") #File path and name
        codeans = ans.find("code", {"class": "brush"}).text #The answer

        # return a compatible tuple
        return ( os.path.join(q,  f'{exer_id}_template', *codepath),
                 io.BytesIO(codeans.encode(encoding='UTF-8') )

并基于元组列表定义在内存zip中创建的业务函数。这应该从第一个项目获取文件路径,并相应地在zip文件中创建该文件夹结构

import zipfile

def get_zip_buffer(list_of_tuples):
    zip_buffer = io.BytesIO()
    
    # https://stackoverflow.com/a/44946732 <3   
    with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file:
        for file_name, data in list_of_tuples:
            zip_file.writestr(file_name, data.read())

    zip_buffer.seek(0)
    return zip_buffer

要在Flask中实现这一点,您可能有如下下载路径:

@app.route('/downloader')
def download():
    list_of_tuples = [process_individual(a) for a in individual_ans]
    buff = get_zip_buffer(list_of_tuples)
    
    return send_file(buff,
                     mimetype='application/zip',
                     as_attachment=True,
                     attachment_filename='memoryzip.zip')

我还没有用你的输入数据测试过,所以可能需要稍微调整一下。希望这能有所帮助

相关问题 更多 >