在 Tornado 中,如何 'decorate' 协程 GET 函数

In Tornado, How to 'decorate' a coroutine GET function

我想修饰GET协程方法,判断是否需要从缓存中读取数据并将数据设置到缓存中。但我不知道如何包装协程。这是我现在的做法:

def cache_it(f):
    @functools.wraps(f)
    @coroutine
    def wrapper(self, *args, **kwargs):
        key = self.get_cache_key()
        result = cache.get(key)
        if not result:
            yield f(self, *args, **kwargs)
            if self._result_buffer:
                cache.set(key, self._result_buffer)
        else:
            self._result_buffer = result 

class BaseHandler(RequestHandler):
    def __init__(self, *args, **kwargs):
        super(BaseHandler, self).__init__(*args, **kwargs)
        self._result_buffer = []

    def write(self, chunk):
        self._result_buffer.append(chunk)

    def flush(self, include_footers=False, callback=None):
        self._flush_result_buffer()
        super(BaseHandler, self).flush(include_footers)

    def finish(self, chunk=None):
        if chunk is not None:
            self.write(chunk)
        self._flush_result_buffer()
        super(BaseHandler, self).finish()

    def _flush_result_buffer(self):
        for r in self._result_buffer:
            super(BaseHandler, self).write(r)
        self._result_buffer = []

class IndexHandler(RequestHandler):

    @cache_it
    @coroutine
    def get(self):
        ...
        self.write({'data': data})

但它不起作用。请让我知道该怎么做以及我哪里错了。

首先。 协程应该是固定的(只需添加return):

def cache_it(f):
    @functools.wraps(f)
    @coroutine
    def wrapper(self, *args, **kwargs):
        key = self.get_cache_key()
        result = cache.get(key)
        if not result:
            yield f(self, *args, **kwargs)
            if self._result_buffer:
                cache.set(key, self._result_buffer)
        else:
            self._result_buffer = result 
    return wrapper

这里也应该修复:

class IndexHandler(BaseHandler):

现在您可以缓存结果缓冲区(注意:它是列表)。