Why call clearup code in generator function?
guys. I'm reading web.py source code to understand how WSGI frameworks work.
When reading application.py module, I wonder why call self._cleanup in cleanup which is a generator function.
I searched reasons to use generator, like this, but I'm n开发者_运维百科ot sure why use generator here.
Here is the code block:
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())
What itertools.chain(result, cleanup())
does is effectively
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
The only reason I can imagine why it's written in such a weird way is to avoid that extra pure Python loop for a little bit of performance.
精彩评论