0

伙计们。我正在阅读 web.py 源代码以了解 WSGI 框架的工作原理。

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

我搜索了使用生成器的原因,就像这样,但我不确定为什么在这里使用生成器。

这是代码块:

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

1 回答 1

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 循环以获得一点性能。

于 2011-05-03T14:15:26.137 回答