樱桃py自动下载文件

cherry py auto download file

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

zip文件生成完成后,我要开始下载到客户端 所以创建图像后,将它们压缩并发送给客户端

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

只需在内存中创建一个 zip 存档,然后使用 cherrypy.lib 中的 file_generator() 辅助函数 return 它。您也可以 yield HTTP 响应以启用流式传输功能(请记住在执行此操作之前设置 HTTP headers)。 我为你写了一个简单的例子(基于你的代码片段) returning 整个缓冲的 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)

N.B。我没有测试这段具体的代码,但总体思路是正确的。