简体   繁体   中英

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

I want to decorates the GET coroutine method, which determines whether needs to read the data from cache and set the data to cache. But i don't know how to wrap a coroutine. Here is how i do it now:

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

But it's not working. Please let me know how to do it and where i'm wrong.

Af first. coroutine should be fixed(Just add 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

And here also should be fixed:

class IndexHandler(BaseHandler):

Now you can cache result buffer(note: it's list).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM