middleware
middleware 是一种拦截器,一个URL在被某个函数处理前,可以经过一系列的 middleware 的处理。
一个 middleware 可以改变URL的输入、输出,甚至可以决定不继续处理而直接返回。middleware的用处就在于把通用的功能从每个URL处理函数中拿出来,集中放到一个地方。例如,一个记录URL日志的 logger 可以简单定义如下:
@asyncio.coroutine
def logger_factory(app, handler):
@asyncio.coroutine
def logger(request):
# 记录日志:
logging.info('Request: %s %s' % (request.method, request.path))
# 继续处理请求:
return (yield from handler(request))
return logger
而 response 这个 middleware 把返回值转换为 web.Response 对象再返回,以保证满足 aiohttp 的要求:
@asyncio.coroutine
def response_factory(app, handler):
@asyncio.coroutine
def response(request):
# 结果:
r = yield from handler(request)
if isinstance(r, web.StreamResponse):
return r
if isinstance(r, bytes):
resp = web.Response(body=r)
resp.content_type = 'application/octet-stream'
return resp
if isinstance(r, str):
resp = web.Response(body=r.encode('utf-8'))
resp.content_type = 'text/html;charset=utf-8'
return resp
if isinstance(r, dict):
…
有了这些基础设施,我们就可以专注地往 handlers 模块不断添加URL处理函数了,可以极大地提高开发效率。