2014-10-02 83 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