NameError:未定义全局名称
|
你好
我的错误是在生成zip文件时产生的。你能告诉我该怎么做吗?
main.py\", line 2289, in get
buf=zipf.read(2048)
NameError: global name \'zipf\' is not defined
完整的代码如下:
def addFile(self,zipstream,url,fname):
# get the contents
result = urlfetch.fetch(url)
# store the contents in a stream
f=StringIO.StringIO(result.content)
length = result.headers[\'Content-Length\']
f.seek(0)
# write the contents to the zip file
while True:
buff = f.read(int(length))
if buff==\"\":break
zipstream.writestr(fname,buff)
return zipstream
def get(self):
self.response.headers[\"Cache-Control\"] = \"public,max-age=%s\" % 86400
start=datetime.datetime.now()-timedelta(days=20)
count = int(self.request.get(\'count\')) if not self.request.get(\'count\')==\'\' else 1000
from google.appengine.api import memcache
memcache_key = \"ads\"
data = memcache.get(memcache_key)
if data is None:
a= Ad.all().filter(\"modified >\", start).filter(\"url IN\", [\'www.koolbusiness.com\']).filter(\"published =\", True).order(\"-modified\").fetch(count)
memcache.set(\"ads\", a)
else:
a = data
dispatch=\'templates/kml.html\'
template_values = {\'a\': a , \'request\':self.request,}
path = os.path.join(os.path.dirname(__file__), dispatch)
output = template.render(path, template_values)
self.response.headers[\'Content-Length\'] = len(output)
zipstream=StringIO.StringIO()
file = zipfile.ZipFile(zipstream,\"w\")
url = \'http://www.koolbusiness.com/list.kml\'
# repeat this for every URL that should be added to the zipfile
file =self.addFile(file,url,\"list.kml\")
# we have finished with the zip so package it up and write the directory
file.close()
zipstream.seek(0)
# create and return the output stream
self.response.headers[\'Content-Type\'] =\'application/zip\'
self.response.headers[\'Content-Disposition\'] = \'attachment; filename=\"list.kmz\"\'
while True:
buf=zipf.read(2048)
if buf==\"\": break
self.response.out.write(buf)
没有找到相关结果
已邀请:
3 个回复
杭难插
久坡
: zipfile.ZipFile类(文件[,模式[,压缩[,allowZip64]]]) 打开一个ZIP文件,其中file可以是文件的路径(字符串)或 类似于文件的对象。模式参数 应该是“ r”以读取现有的 文件'w \'截断并编写新文件 文件,或“ a”以附加到现有文件 文件。如果mode为\'a \'并且文件引用 到现有的ZIP文件,然后 其他文件将添加到其中。如果 文件不引用ZIP文件, 然后将新的ZIP存档附加到 文件。这是为了添加一个 ZIP存档到另一个文件(例如 python.exe)。 您的代码:
使用StringIO创建一个类似文件的对象,该对象本质上是一个“内存文件”,更多内容参见ѭ7
以\'w \'模式打开带有zipstream类文件对象的zipfile
使用addFile方法检索检索到的数据并将其写入类似文件的对象,然后将其返回。因为将zipfile传递给别名为zipstream的addFile方法,所以变量有点令人困惑(因为我们将zipstream用作类似StringIO文件的对象,所以令人困惑)。无论如何,将返回zipfile,并关闭该zip文件以确保所有内容都被“写入”。 它被写入到我们的“内存文件”中,现在我们寻求索引0
在完成头文件之后,我们终于到达了while循环,它将以块的形式读取我们的“内存文件”
械怒等
在你之后
线。您正在修改全局变量,这是python知道您在做什么的唯一方法。