简体   繁体   English

NameError:全局名称未定义

[英]NameError: global name is not defined

Hello My error is produced in generating a zip file. 您好我的错误是在生成zip文件时产生的。 Can you inform what I should do? 你能告诉我该怎么做吗?

main.py", line 2289, in get
    buf=zipf.read(2048)
NameError: global name 'zipf' is not defined

The complete code is as follows: 完整的代码如下:

 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)

That is probably zipstream and not zipf . 那可能是zipstream而不是zipf So replace that with zipstream and it might work. 因此,将其替换为zipstream ,它可能会起作用。

i don't see where you declare zipf? 我看不到您在哪里声明zipf?

zipfile? zip文件? Senthil Kumaran is probably right with zipstream since you seek(0) on zipstream before the while loop to read chunks of the mystery variable. Senthil Kumaran可能对zipstream正确,因为您在while循环之前在zipstream上寻求(0)来读取神秘变量的块。

edit: 编辑:

Almost certainly the variable is zipstream. 几乎可以肯定,该变量是zipstream。

zipfile docs : zipfile docs

class zipfile.ZipFile(file[, mode[, compression[, allowZip64]]]) zipfile.ZipFile类(文件[,模式[,压缩[,allowZip64]]])

Open a ZIP file, where file can be either a path to a file (a string) or a file-like object. 打开一个ZIP文件,其中file可以是文件的路径(字符串)或类似文件的对象。 The mode parameter should be 'r' to read an existing file, 'w' to truncate and write a new file, or 'a' to append to an existing file. 模式参数应为“ r”以读取现有文件,为“ w”以截断并写入新文件,或为“ a”以附加到现有文件。 If mode is 'a' and file refers to an existing ZIP file, then additional files are added to it. 如果mode为'a'并且文件引用现有的ZIP文件,则将其他文件添加到其中。 If file does not refer to a ZIP file, then a new ZIP archive is appended to the file. 如果文件不引用ZIP文件,则将新的ZIP存档附加到文件中。 This is meant for adding a ZIP archive to another file (such as python.exe). 这是为了将ZIP归档文件添加到另一个文件(例如python.exe)。

your code: 您的代码:

zipsteam=StringIO.StringIO() 

create a file-like object using StringIO which is essentially a "memory file" read more in docs 使用StringIO创建一个类似文件的对象,该对象本质上是一个“内存文件”,在docs了解更多

file = zipfile.ZipFile(zipstream,w)

opens the zipfile with the zipstream file-like object in 'w' mode 在“ w”模式下打开带有类似zipstream文件的对象的zipfile

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()

uses the addFile method to retrieve and write the retrieved data to the file-like object and returns it. 使用addFile方法检索检索到的数据并将其写入类似文件的对象,然后将其返回。 The variables are slightly confusing because you pass a zipfile to the addFile method which aliases as zipstream (confusing because we are using zipstream as a StringIO file-like object). 因为将zipfile传递给别名为zipstream的addFile方法,所以变量有点令人困惑(因为我们将zipstream用作类似StringIO文件的对象,所以令人困惑)。 Anyways, the zipfile is returned, and closed to make sure everything is "written". 无论如何,将返回zipfile,并关闭该zip文件以确保所有内容均已“写入”。

It was written to our "memory file", which we now seek to index 0 它被写入到我们的“内存文件”中,现在我们寻求索引0

zipstream.seek(0)

and after doing some header stuff, we finally reach the while loop that will read our "memory-file" in chunks 在完成头文件之后,我们最终到达while循环,它将以块的形式读取“内存文件”

while True:
    buf=zipstream.read(2048)
    if buf=="": break
    self.response.out.write(buf)

You need to declare: 您需要声明:

global zipf

right after your def get(self): 在您的def get(self):

line. 线。 you are modifying a global variable, and this is the only way python knows what you are doing. 您正在修改全局变量,这是python知道您在做什么的唯一方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM