每次我点击刷新时都会“打印”For循环

2024-04-25 01:38:36 发布

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

我用CherryPy和Jinja2建立了一个简单的网页

webserver python文件:

import cherrypy
from jinja2 import Environment, FileSystemLoader
from soltyslib import listFiles
env = Environment(loader=FileSystemLoader('templates'))
class HelloWorld(object):   
    @cherrypy.expose        
    def index(self):        
        template = env.get_template('index.html')
        result = template.render(name='Pawel',files=listFiles('templates'))
        return result    

cherrypy.quickstart(HelloWorld())

模板文件:

^{pr2}$

好的,然后我运行webserver,转到127.0.0.1:8080,看到预期的结果:

Hello Pawel!

  • templates\index.html
  • templates\list.html

但我在浏览器中点击刷新,结果是:

Hello Pawel!

  • templates\index.html
  • templates\list.html
  • templates\index.html
  • templates\list.html

为什么?for循环是否再次求值?如何防止这样做?在

想知道某个文件的功能是什么:

import os,sys
from collections import deque
def listFiles(cdir, fileslist=[]):
    basedir = cdir
    queuedir = deque()
    queuedir.append(basedir)
    while len(queuedir) > 0:
        currentbase = queuedir.popleft()
        for f in os.listdir(currentbase):
            f = os.path.join(currentbase,f)
            if os.path.isdir(f):           
                queuedir.append(f)
            else:
                fileslist.append(f)

    return fileslist

Tags: 文件fromimportindexoshtmltemplatetemplates
3条回答

它是listFilesfileslist的默认kwarg。该列表在模块加载时创建一次,并在附加时不断累积项目。在

你的问题是

 def listFiles(cdir, fileslist=[]):

每次调用都要重用相同的列表,因为只有在定义函数时才计算默认参数,而不是每次调用函数时才计算默认参数。有关此行为的详细讨论,请参见"Least Astonishment" and the Mutable Default Argument。在

^{pr2}$

您的问题在函数声明的fileslist=[]中。默认值只计算一次,这意味着列表是在第一次调用时创建的,但从不重建或清除。在

相关问题 更多 >