2017-12-05 29 views
1

내 aiohttp 미들웨어는 경로로 전달 된 바인딩 된 메서드 대신 매개 변수로 함수를 가져옵니다. 이 행동을 설명하는 방법? 어떻게 피하는거야? 핸들러 클래스로 구성되어 및 경로로 전달 된 경우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' 
+0

이것은 'asyncio.coroutine'의 작동 방식입니다. –

+0

aiohttp가 도움을받지 않고 코 루틴 꾸미기에 내 미들웨어를 래핑한다는 뜻입니까? 나는 당신의 공헌에 대해 "고맙다"라고 말할 기회를가집니다. – VadimFilin

+0

예를보세요. '@ asyncio.coroutine' 데코레이터에 의해'preprocess_request'를 명시 적으로 감싸고 있습니다. –

답변

2

, partial.wraps을 사용하여 장식과 그 핸들러를 감싸고 일반적인 기능처럼 만들어aiohttp. 따라서이 함수를 객체 메소드로 직접 사용하는 것은 불가능합니다.

그들은 단지 언 래핑 후 방법으로 사용될 수

: 그것은 MutableMapping 프로토콜 때문에

handler.__wrapped__.__self__ 

또는 핸들러 클래스 web.Application (로 전달 될 수있다) 값 :

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

을 할 수있다

class_handler = request.app["handler"]