2011-05-03 61 views
0

伙计。我正在阅读web.py源代码以了解WSGI框架如何工作。为什么在生成器函数中调用清除代码?

当读取application.py模块时,我想知道为什么在清理中调用self._cleanup这是一个生成器函数。

我搜索使用生成器的原因,如this,但我不知道为什么在这里使用生成器。

这里是代码块:

def wsgi(env, start_resp): 
    # clear threadlocal to avoid inteference of previous requests 
    self._cleanup() 

    self.load(env) 
    try: 
     # allow uppercase methods only 
     if web.ctx.method.upper() != web.ctx.method: 
      raise web.nomethod() 

     result = self.handle_with_processors() 
     if is_generator(result): 
      result = peep(result) 
     else: 
      result = [result] 
    except web.HTTPError, e: 
     result = [e.data] 

    result = web.utf8(iter(result)) 

    status, headers = web.ctx.status, web.ctx.headers 
    start_resp(status, headers) 

    def cleanup(): 
     self._cleanup() 
     yield '' # force this function to be a generator 

    return itertools.chain(result, cleanup()) 

回答

1

做什么itertools.chain(result, cleanup())实际上是

def wsgi(env, start_resp): 
    [...] 

    status, headers = web.ctx.status, web.ctx.headers 
    start_resp(status, headers) 

    for part in result: 
     yield part 
    self._cleanup() 
    # yield '' # you'd skip this line because it's pointless 

我能想象它为什么写得这么奇怪的是,唯一的原因是为了避免额外的纯Python循环一点点的表现。

+0

感谢您的回复。这是合理的。我重新思考代码,我猜想另一个原因是尽快将结果返回给客户端,然后再做清理工作以避免延迟。不确定是否正确。 – 2011-05-03 15:53:02

相关问题