Django模板过滤器上的装饰器?

时间:2009-12-04 19:47:01

标签: python django django-templates filter templatetags

我有一个模板过滤器,它执行一个非常简单的任务并且运行良好,但我想在它上面使用装饰器。不幸的是,装饰器导致一个令人讨厌的django错误,没有任何意义......

有效的代码:

@register.filter(name="has_network")
def has_network(profile, network):
    hasnetworkfunc = getattr(profile, "has_%s" % network)
    return hasnetworkfunc()

使用装饰器(不起作用):

@register.filter(name="has_network")
@cache_function(30)
def has_network(profile, network):
    hasnetworkfunc = getattr(profile, "has_%s" % network)
    return hasnetworkfunc()

这是错误:

  

处的TemplateSyntaxError      

渲染时捕获异常:   从空列表中弹出

我已经尝试在装饰器内设置断点,我有理由相信它甚至没有被调用......

但以防万一这里是装饰者(我知道会有人要求)

我用一个什么也没做的模拟装饰器替换装饰器(暂时),但我仍然得到同样的错误

def cache_function(cache_timeout):
    def wrapper(fn):
        def decorator(*args, **kwargs):
            return fn(*args, **kwargs)
        return decorator
    return wrapper

编辑确认 :这是因为装饰器需要*args**kwargs?我假设正在调用pop()以确保过滤器都至少采用一个arg?

将装饰器更改为此可以解决问题:

def cache_function(cache_timeout):
    def wrapper(fn):
        def decorator(arg1, arg2):
            return fn(arg1, arg2)
        return decorator
    return wrapper

不幸的是,这破坏了装饰者的一般性质:/现在该做什么?

1 个答案:

答案 0 :(得分:0)

最终答案:向装饰者添加一个额外的参数,指出正在装饰的内容

可能有更优雅的东西,但这很有效。

from django.core.cache import cache
from django.db.models.query import QuerySet
try:
    from cPickle import dumps
except:
    from pickle import dumps
from hashlib import sha1

cache_miss = object()

class CantPickleAQuerySet(Exception): pass

def cache_function(cache_timeout, func_type='generic'):
    def wrapper(fn):
        def decorator(*args, **kwargs):
            try:
                cache_indentifiers = "%s%s%s%s" % (
                                         fn.__module__,
                                         fn.__name__,
                                         dumps(args),
                                         dumps(kwargs)
                                         )
            except Exception, e:
                print "Error: %s\nFailed to generate cache key: %s%s" % (e, fn.__module__, fn.__name__)
                return fn(*args, **kwargs)

            cache_key = sha1(cache_indentifiers).hexdigest()

            value = cache.get(cache_key, cache_miss)

            if value is cache_miss:
                value = fn(*args, **kwargs)

                if isinstance(value, QuerySet):
                    raise CantPickleAQuerySet("You can't cache a queryset. But you CAN cache a list! just convert your Queryset (the value you were returning) to a list like so `return list(queryset)`")

                try:
                    cache.set(cache_key, value, cache_timeout)
                except Exception, e:
                    print "Error: %s\nFailed to cache: %s\nvalue: %s" % (e, cache_indentifiers, value)

            return value

        no_arg2 = object()
        def filter_decorator(arg1, arg2=no_arg2):
            if arg2 is no_arg2:
                return decorator(arg1)
            else:
                return decorator(arg1, arg2)

        if func_type == 'generic':
            return decorator

        elif func_type == 'filter':
            return filter_decorator

    return wrapper