cherry py自动下载fi

2024-05-16 01:17:22 发布

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

我目前正在为我的项目构建cherry py应用程序,在某些功能上我需要自动启动下载一个文件。在

压缩文件生成完成后,我想开始下载到客户端 所以在图像被创建之后,它们被压缩并发送到客户端

class Process(object):
    exposed = True

    def GET(self, id, norm_all=True, format_ramp=None):
        ...
        def content(): #generating images
            ...

            def zipdir(basedir, archivename):
                assert os.path.isdir(basedir)
                with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z:
                    for root, dirs, files in os.walk(basedir):
                        #NOTE: ignore empty directories
                        for fn in files:
                            absfn = os.path.join(root, fn)
                            zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path
                            z.write(absfn, zfn)

            zipdir("/data/images/8","8.zip")

            #after zip file finish generating, I want to start downloading to client
            #so after images are created, they are zipped and sent to client
            #and I'm thinking do it here, but don't know how

        return content()

    GET._cp_config = {'response.stream': True}


    def POST(self):
        global proc
        global processing
        proc.kill()
        processing = False

Tags: topathselftrue客户端getosdef
1条回答
网友
1楼 · 发布于 2024-05-16 01:17:22

只需在内存中创建一个zip存档,然后使用file_generator()助手函数从cherrypy.lib返回它。您也可以使用yieldHTTP响应来启用流功能(记住在执行此操作之前设置HTTP头)。 我为您编写了一个简单的示例(基于您的代码片段),它只是return整个缓冲zip存档。在

from io import BytesIO

import cherrypy
from cherrypy.lib import file_generator


class GenerateZip:
    @cherrypy.expose
    def archive(self, filename):
        zip_archive = BytesIO()
        with closed(ZipFile(zip_archive, "w", ZIP_DEFLATED)) as z:
            for root, dirs, files in os.walk(basedir):
                #NOTE: ignore empty directories
                for fn in files:
                    absfn = os.path.join(root, fn)
                    zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path
                    z.write(absfn, zfn)


        cherrypy.response.headers['Content-Type'] = (
            'application/zip'
        )
        cherrypy.response.headers['Content-Disposition'] = (
            'attachment; filename={fname}.zip'.format(
                fname=filename
            )
        )

        return file_generator(zip_archive)

注:我没有测试这段代码,但总体思路是正确的。在

相关问题 更多 >