具有cache_page错误的Django自定义装饰器

时间:2013-08-29 11:51:58

标签: python django django-views django-1.5 python-decorators

我在视图上有一个自定义装饰器,我必须在处理一些请求变量后缓存该视图。我的装饰师代码是这样的

def custom_dec(view_func):
    @wraps(view_func, assigned=available_attrs(view_func))
    def wrapper(request,filters,*args,**kwargs):
        # do some processing on request and filters
        return csrf_exempt(cache_page(900, view_func))
return wrapper

我将装饰器应用为:

@custom_dec
def myview(request,filters,*args,**kwargs):
    # view code here

问题是运行此代码在通过中间件时给出了错误:

异常类型:AttributeError
异常值:'function'对象没有属性'status_code'

当我看到响应时,它是功能myview而不是视图的响应 回复<function myview at 0xb549e534>

我的代码有什么问题?

更新:如果我将warpper函数的返回值更改为,则代码运行正常  return view_func这意味着我在应用缓存页面装饰器时必须做错事。

1 个答案:

答案 0 :(得分:0)

原来我必须返回一个HttpResponse对象。当我将代码更改为:

时,它工作正常
def custom_dec(view_func):
    @wraps(view_func, assigned=available_attrs(view_func))
    def wrapper(request,filters,*args,**kwargs):
        # do some processing on request and filters
        cached_func = cache_page(900, view_func)
        return cached_func(request,filters,*args,**kwargs) #this returns an HttpResponse object
        # the above two line could also be written as cache_page(900, view_func)(request,filters,*args,**kwargs)
return wrapper