2016-05-06 36 views
2

根據文檔Python是怎樣aiohttp.web中間件工作

到中間件工廠通過了處理程序是由下一個中間件廠家返回的句柄。最後一箇中間件工廠總是接收由路由器本身選擇的請求處理程序(由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中間件作爲處理

回答

3

中間件沒有返回,但中間件處理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的演講,介紹了新語法。