gpt4 book ai didi

python - python aiohttp.web 中间件如何工作

转载 作者:行者123 更新时间:2023-11-28 16:25:37 27 4
gpt4 key购买 nike

根据文档

The handler passed in to a middleware factory is the handler returned by the next middleware factory. The last middleware factory always receives the request handler selected by the router itself (by UrlDispatcher.resolve()).

我认为 UrlDispatcher.resolve() 会返回我分配的已注册处理程序,所以我编写了这段代码。根据我的理解,当访问页面 127.0.0.1:9000 时,索引处理程序将用作 m1 的处理程序

import logging;
import asyncio
from aiohttp import web

logging.basicConfig(level=logging.INFO)

@asyncio.coroutine
def m1(app,handler):
def log(request):
r = yield from handler(request)
logging.info(str(r))

@asyncio.coroutine
def index(request):
return web.Response(body=b'<h1>Aswesome</h1>')

@asyncio.coroutine
def names(request):
return web.Response(text='<h1>%s</h1>' % request.match_info['name'])

@asyncio.coroutine
def init(loop):
app = web.Application(loop=loop, middlewares=[
m1
])
app.router.add_route('GET','/',index)
app.router.add_route('GET','/{name:\w+}',names)
srv = yield from loop.create_server(app.make_handler(),'127.0.0.1',9000)
logging.info('server started at http://127.0.0.1:9000')
return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()

当我运行代码并访问 127.0.0.1:9000 的服务器时,我得到了

  File "/home/os/Documents/Python/web/lib/python3.5/site-packages/aiohttp/web.py", line 90, in handle_request
resp = yield from handler(request)
TypeError: 'NoneType' object is not callable

在我看来,NoneType 作为处理程序传递到 m1 中间件

最佳答案

您的中间件不返回任何内容,但应该返回中间件处理程序 log。我在您的代码中添加了一行,它返回 log

@asyncio.coroutine
def m1(app,handler):
def log(request):
r = yield from handler(request)
logging.info(str(r))
return log # changed

参见 documentation regarding middlewares更多细节。此外,值得研究一下 Python 3.5,它提供了 async/await 语法来处理可等待对象,也就是协程。 aiohttp 的贡献者建议使用语法。

见官方PEP-492slides来自 Igor Davydenko 对新语法的介绍。

关于python - python aiohttp.web 中间件如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37082656/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com