tunaktunak tunaktunak - 4 months ago 16
Python Question

Python Decorators - <Classname> object has no attribute '__name__'

I have a tornado method like below and I tried to decorate method to cache stuff. I have the following setup

def request_cacher(x):
def wrapper(funca):
@functools.wraps(funca)
@asynchronous
@coroutine
def wrapped_f(self, *args, **kwargs):
pass

return wrapped_f
return wrapper

class PhotoListHandler(BaseHandler):
@request_cacher
@auth_required
@asynchronous
@coroutine
def get(self):
pass


I am receiving the error,
AttributeError: 'PhotoListHandler' object has no attribute '__name__'

Any ideas?

Answer

i think this might work for you,

import tornado.ioloop
import tornado.web
from tornado.gen import coroutine
from functools import wraps


cache = {}

class cached(object):
    def __init__ (self, rule, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        self.rule = rule
        cache[rule] = 'xxx'

    def __call__(self, fn):
        def newf(*args, **kwargs):
            slf = args[0]
            if cache.get(self.rule):
                slf.write(cache.get(self.rule))
                return
            return fn(*args, **kwargs)
        return newf 


class MainHandler(tornado.web.RequestHandler):

    @coroutine
    @cached('/foo')
    def get(self):
        print "helloo"
        self.write("Hello, world")

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
Comments