NameError:未定义全局名称

发布于 2024-11-02 04:29:08 字数 2131 浏览 1 评论 0原文

你好 我的错误是在生成 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)

Hello
My error is produced in generating a zip file. 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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

过去的过去 2024-11-09 04:29:09

这可能是 zipstream 而不是 zipf。因此,将其替换为 zipstream 可能会起作用。

That is probably zipstream and not zipf. So replace that with zipstream and it might work.

溺孤伤于心 2024-11-09 04:29:09

我不明白你在哪里声明 zipf ?

压缩文件? Senthil Kumaran 对 zipstream 的看法可能是正确的,因为您在 while 循环之前在 zipstream 上查找(0) 来读取神秘变量的块。

编辑:

几乎可以肯定该变量是 zipstream。

zipfile 文档

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

打开一个 ZIP 文件,其中 file 可以是文件的路径(字符串)或
类似文件的对象。模式参数
应该是“r”来读取现有的
文件,'w' 截断并写入新的
文件,或“a”附加到现有的
文件。如果模式为“a”并且文件引用
到现有的 ZIP 文件,然后
附加文件将添加到其中。如果
文件不引用 ZIP 文件,
然后一个新的 ZIP 存档被附加到
文件。这是为了添加一个
ZIP 存档到另一个文件(例如
python.exe)。

您的代码:

zipsteam=StringIO.StringIO() 

使用 StringIO 创建一个类似文件的对象,它本质上是一个“内存文件”,请阅读 < strong>docs

file = zipfile.ZipFile(zipstream,w)

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

使用 addFile 方法检索并将检索到的数据写入类文件对象并返回它。这些变量有点令人困惑,因为您将 zipfile 传递给 addFile 方法,该方法别名为 zipstream(令人困惑,因为我们使用 zipstream 作为 StringIO 文件类对象)。无论如何,zip 文件将被返回并关闭以确保所有内容都已“写入”。

它被写入我们的“内存文件”,我们现在寻求索引 0

zipstream.seek(0)

,并且在做了一些头文件之后,我们最终到达 while 循环,它将以块的形式读取我们的“内存文件”

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

i don't see where you declare zipf?

zipfile? Senthil Kumaran is probably right with zipstream since you seek(0) on zipstream before the while loop to read chunks of the mystery variable.

edit:

Almost certainly the variable is zipstream.

zipfile docs:

class zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])

Open a ZIP file, where file can be either a path to a file (a string) or
a file-like object. 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. If mode is 'a' and file refers
to an existing ZIP file, then
additional files are added to it. If
file does not refer to a ZIP file,
then a new ZIP archive is appended to
the file. This is meant for adding a
ZIP archive to another file (such as
python.exe).

your code:

zipsteam=StringIO.StringIO() 

create a file-like object using StringIO which is essentially a "memory file" read more in docs

file = zipfile.ZipFile(zipstream,w)

opens the zipfile with the zipstream file-like object in 'w' mode

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. 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). Anyways, the zipfile is returned, and closed to make sure everything is "written".

It was written to our "memory file", which we now seek to index 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 True:
    buf=zipstream.read(2048)
    if buf=="": break
    self.response.out.write(buf)
慵挽 2024-11-09 04:29:09

您需要声明:

global zipf

紧随您之后
def get(self):

行。你正在修改一个全局变量,这是Python知道你在做什么的唯一方法。

You need to declare:

global zipf

right after your
def get(self):

line. you are modifying a global variable, and this is the only way python knows what you are doing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文