cherry py自动下载文件

时间:2016-06-29 22:57:29

标签: python cherrypy

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

生成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

1 个答案:

答案 0 :(得分:0)

只需在内存中创建一个zip存档,然后使用file_generator()中的cherrypy.lib辅助函数返回它。您也可以使用yield HTTP响应来启用流功能(请记住在执行此操作之前设置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)

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