我想装饰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})
但它不起作用。请让我知道怎么做以及我错了。
答案 0 :(得分:2)
Af首先。 coroutine应该修复(只需添加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):
现在你可以缓存结果缓冲区(注意:它的列表)。