【问题标题】:Django custom decorator with cache_page error带有cache_page错误的Django自定义装饰器
【发布时间】:2013-09-01 20:15:15
【问题描述】:

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

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'

当我查看 at 响应时,它是函数 myview 而不是视图的响应。
回复<function myview at 0xb549e534>

我的代码有什么问题?

更新:如果我将 warpper 函数中的返回更改为 return view_func 这意味着我在应用缓存页面装饰器时一定做错了。

【问题讨论】:

  • 您是否正在从您的视图中返回 HttpResonse 对象?按原样在此处发布完整视图代码。
  • @SrinivasReddyThatiparthy :是的,视图代码在没有这个装饰器的情况下工作。
  • Nope.In那种情况下它不起作用。即使您正在缓存,您也需要从该视图返回 HttpResponse 对象。
  • @SrinivasReddyThatiparthy 我不明白,该视图使用 render_to_response 渲染模板。我在视图上使用了简单的缓存(900)装饰器,它工作。这个自定义装饰器给我带来了问题。
  • 那是因为你是返回函数,而不是响应对象。

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


【解决方案1】:

原来我必须返回一个 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 

【讨论】:

    猜你喜欢
    • 2015-03-25
    • 2018-11-21
    • 2017-08-28
    • 2019-07-19
    • 2014-06-07
    • 1970-01-01
    • 2013-02-06
    • 2011-10-16
    • 1970-01-01
    相关资源
    最近更新 更多