2014-10-02 2 views
0

토네이도에서 비동기 함수와 모호한 상황에 직면했습니다.함수에서 비동기 액션 캡슐화

내가해온 시스템은 POST 요청 만 받고 비동기 적으로 제공됩니다. 하지만 이제 IE8 사용자에게 서비스를 제공하기 위해 GET 요청 처리를 추가해야합니다. 문제는 GET 요청 기능이 게시 요청과 정확하게 일치하여 입니다. 내가 공동 원하지 않는

단순히-복사 붙여 넣기 내 코드를, 그래서 나는 다음과 같은 솔루션에 온했습니다

class ExampleHandler(BaseHandler): 

    def _request_action(self): 
     """ Function that incapsulates all actions, that should be performed in request 
     """ 
     yield self.motor.col1.insert({"ex1": 1}) 
     raise Return 

    @gen.coroutine 
    def get(self): 
     """ GET request handler - need for IE8- users. Used ONLY for them 
     """ 
     self._request_action() 

    @gen.coroutine 
    def post(self): 
     """ POST handling for all users, except IE8- 
     """ 
     self._request_action() 

내가 비동기 장식에 대한 의심의 여지가. 데코레이터에서 GET/POST 처리기를 래핑하고 동 기적으로 작동하는 함수에서 수행해야하는 모든 작업을 처리하는 것으로 충분합니까? 아니면 내가 포장해야합니까?

답변

2

yieldFuture을 함수 내에 넣으려면 @gen.coroutine으로 묶어야합니다.

그래서, 또한, 모든 코 루틴이 yield에 의해 호출해야 @gen.coroutine

@gen.coroutine 
def _request_action(self): 
    """ Function that incapsulates all actions, that should be performed in request 
    """ 
    result = yield self.motor.col1.insert({"ex1": 1}) 
    raise gen.Return(result) # that is how you can return result from coroutine 

와 함께 _request_action 포장 :

@gen.coroutine 
def get(self): 
    """ GET request handler - need for IE8- users. Used ONLY for them 
    """ 
    result = yield self._request_action() 
    # do something with result, if you need 

@gen.coroutine 
def post(self): 
    """ POST handling for all users, except IE8- 
    """ 
    result = yield self._request_action() 
    # do something with result, if you need 
+0

대, 덕분에 많이! – privetartyomka

관련 문제