Python 在函数中封装异步操作

Python 在函数中封装异步操作,python,asynchronous,tornado,Python,Asynchronous,Tornado,我在Tornado中遇到了异步函数的模糊情况 我一直在使用的系统只接收POST请求,并异步地为它们提供服务。但现在我必须为服务IE8用户添加GET请求处理。 问题在于GET请求功能与post请求中的功能完全相同 我不想复制粘贴我的代码,所以我采用了以下解决方案: class ExampleHandler(BaseHandler): def _request_action(self): """ Function that incapsulates all actions,

我在Tornado中遇到了异步函数的模糊情况

我一直在使用的系统只接收POST请求,并异步地为它们提供服务。但现在我必须为服务IE8用户添加GET请求处理。 问题在于GET请求功能与post请求中的功能完全相同

我不想复制粘贴我的代码,所以我采用了以下解决方案:

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()

我对异步装饰器有很多疑问。在decorators中包装GET/POST处理程序,并将所有应该执行的操作放在一个同步工作的函数中是否足够?或者我也应该把它包装起来?

如果你
在一个函数中产生了一个
a,你必须用它包装起来

因此,用
@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