aiohttp 隐含地证明我的方法起作用
aiohttp implicitly turns out my method to function
我的 aiohttp 中间件获取函数作为参数而不是传递给路由的绑定方法。如何解释这种行为?如何避免这种情况?
class AsyncHttpServer:
def __init__(self, host=None, port=None, loop=None, conf_path=None):
self.loop = loop
self.conf_path = conf_path
self.host = host
self.port = port
self.loop = loop
self.app = web.Application(
middlewares=[
preprocess_request,
]
)
def serve_forever(self):
with RequestHandler(self.conf_path) as handler:
print(handler.search) # bound method 'search'. Instance is irrelevant
self.app.router.add_routes([
web.post('/search', handler.search, name='search'),
])
try:
web.run_app(self.app, port=self.port, host=self.host, loop=self.loop)
except KeyboardInterrupt:
pass
@asyncio.coroutine
@middleware
def preprocess_request(request, handler):
print(handler) # function 'search'
如果处理程序使用 class 组织并已传递给路由,aiohttp 使用 partial.wraps 并使其像通常的功能一样。所以直接把这个函数当作对象方法是不可能的。
它们只有展开后才能用作方法:
handler.__wrapped__.__self__
或处理程序 class 可以作为 web.Application() 值传递,因为它具有 MutableMapping 协议:
with RequestHandler(self.conf_path) as handler:
self.app["handler"] = handler
可以这样称呼:
class_handler = request.app["handler"]
我的 aiohttp 中间件获取函数作为参数而不是传递给路由的绑定方法。如何解释这种行为?如何避免这种情况?
class AsyncHttpServer:
def __init__(self, host=None, port=None, loop=None, conf_path=None):
self.loop = loop
self.conf_path = conf_path
self.host = host
self.port = port
self.loop = loop
self.app = web.Application(
middlewares=[
preprocess_request,
]
)
def serve_forever(self):
with RequestHandler(self.conf_path) as handler:
print(handler.search) # bound method 'search'. Instance is irrelevant
self.app.router.add_routes([
web.post('/search', handler.search, name='search'),
])
try:
web.run_app(self.app, port=self.port, host=self.host, loop=self.loop)
except KeyboardInterrupt:
pass
@asyncio.coroutine
@middleware
def preprocess_request(request, handler):
print(handler) # function 'search'
如果处理程序使用 class 组织并已传递给路由,aiohttp 使用 partial.wraps 并使其像通常的功能一样。所以直接把这个函数当作对象方法是不可能的。
它们只有展开后才能用作方法:
handler.__wrapped__.__self__
或处理程序 class 可以作为 web.Application() 值传递,因为它具有 MutableMapping 协议:
with RequestHandler(self.conf_path) as handler:
self.app["handler"] = handler
可以这样称呼:
class_handler = request.app["handler"]