2016-06-29 4 views
0

현재 프로젝트를위한 체리 파이 응용 프로그램을 만들고 있는데 특정 기능에서 자동 시작 파일을 다운로드해야합니다. 체리 파이 자동 다운로드 파일

은 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 

답변

0

그냥 메모리에 우편 아카이브를 만든 다음 사용하여 반환 압축 및 클라이언트로 전송됩니다 file_generator() 도우미 기능 : cherrypy.lib. 스트리밍 기능을 사용하려면 HTTP 응답을 yield (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. 이 코드 조각을 테스트하지는 않았지만 일반적인 생각은 맞습니다.