gpt4 book ai didi

python - aiohttp 隐式地使我的方法发挥作用

转载 作者:行者123 更新时间:2023-12-01 02:23:46 35 4
gpt4 key购买 nike

我的 aiohttp 中间件获取函数作为参数,而不是已传递给路由的绑定(bind)方法。如何解释这种行为?如何避免这种情况?

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'

最佳答案

如果处理程序是用类组织的并且已传递给路由,aiohttp 会使用 partial.wraps 用装饰器包装这些处理​​程序,并使其像通常的函数一样。所以不可能直接使用这个函数作为对象方法。

它们只有在解包后才能用作方法:

handler.__wrapped__.__self__

或者处理程序类可以作为 web.Application() 值传递,因为它具有 MutableMapping 协议(protocol):

with RequestHandler(self.conf_path) as handler:
self.app["handler"] = handler

可以这样称呼:

class_handler = request.app["handler"]

关于python - aiohttp 隐式地使我的方法发挥作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47652836/

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