2014-10-02 130 views
0

我在Tornado中遇到了異步函數的模糊情況。在函數中封裝異步操作

我一直在處理的系統只接收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

如果你yield a Future裏面的功能,你必須包裝@gen.coroutine

所以,包裹_request_action@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 

並且也協同程序都必須由yield被稱爲:

@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 2014-10-02 12:50:40