是否可以使用App Engine生成并返回ZIP文件?

2024-04-19 21:58:03 发布

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

我有一个很适合Google App Engine的小项目。实现它取决于生成并返回ZIP文件的能力。

由于App Engine的分布式特性,据我所知,无法在传统意义上的“内存”中创建ZIP文件。它基本上必须在单个请求/响应周期中生成和发送。

Python zip模块甚至存在于App Engine环境中吗?


Tags: 模块文件项目内存app环境google分布式
3条回答

来自What is Google App Engine

You can upload other third-party libraries with your application, as long as they are implemented in pure Python and do not require any unsupported standard library modules.

所以,即使它默认不存在,你也可以(潜在地)自己包含它。(我说可能是因为我不知道Python zip库是否需要任何“不受支持的标准库模块”。

zipfile可在appengine上获得,并重新加工example如下:

from contextlib import closing
from zipfile import ZipFile, ZIP_DEFLATED

from google.appengine.ext import webapp
from google.appengine.api import urlfetch

def addResource(zfile, url, fname):
    # get the contents      
    contents = urlfetch.fetch(url).content
    # write the contents to the zip file
    zfile.writestr(fname, contents)

class OutZipfile(webapp.RequestHandler):
    def get(self):
        # Set up headers for browser to correctly recognize ZIP file
        self.response.headers['Content-Type'] ='application/zip'
        self.response.headers['Content-Disposition'] = \
            'attachment; filename="outfile.zip"'    

        # compress files and emit them directly to HTTP response stream
        with closing(ZipFile(self.response.out, "w", ZIP_DEFLATED)) as outfile:
            # repeat this for every URL that should be added to the zipfile
            addResource(outfile, 
                'https://www.google.com/intl/en/policies/privacy/', 
                'privacy.html')
            addResource(outfile, 
                'https://www.google.com/intl/en/policies/terms/', 
                'terms.html')
import zipfile
import StringIO

text = u"ABCDEFGHIJKLMNOPQRSTUVWXYVabcdefghijklmnopqqstuvweyxáéöüï东 廣 広 广 國 国 国 界"

zipstream=StringIO.StringIO()
file = zipfile.ZipFile(file=zipstream,compression=zipfile.ZIP_DEFLATED,mode="w")
file.writestr("data.txt.zip",text.encode("utf-8"))
file.close()
zipstream.seek(0)
self.response.headers['Content-Type'] ='application/zip'
self.response.headers['Content-Disposition'] = 'attachment; filename="data.txt.zip"'
self.response.out.write(zipstream.getvalue())

相关问题 更多 >