vkill'blog

“技术本身没有太多价值,掌握了新的思考方式才是真的收获”

use cache_page error ViewClass instance has no attribute 'method'

10:14 , vkill
当我们在 类实例方法/类方法 中使用装饰器 cache_page 的时候,如下面这样

class PersonView(ViewBase):
    @cache_page(60 * 15)
    def index(self, request, *args, **kwargs):
        persons = Person.objects.select_related()
        return list_detail.object_list(
            request,
            queryset = persons,
            template_name = "person/index.html",
            paginate_by = 3,
            extra_context = {'string':'aaa'}
        )


此时就会提示下面这个错误
Quotation

ViewClass instance has no attribute 'method'


发生在 Python27\lib\site-packages\django\middleware\cache.py in process_request, line 138
看了下位置意思是 request.method 这个错了

之前想过,django自带的那些装饰器都是针对 函数 的,而类实例方法多了个 self 参数,自然用django自带的那些会出错的,至少从理论上来说是这样
google 了,搜索到这篇文章
http://www.toddreed.name/content/django-view-class/
很巧妙的给django自带的装饰器外再套一层装饰器使用,这个方法很不错,哈哈

新定义的装饰器

def on_method(function_decorator):
    def decorate_method(unbound_method):
        def method_proxy(self, *args, **kwargs):
            def f(*a, **kw):
                return unbound_method(self, *a, **kw)
            return function_decorator(f)(*args, **kwargs)
        return method_proxy
    return decorate_method


类实例方法中使用django自带装饰器

class PersonView(ViewBase):
    @on_method(cache_page(60 * 15))
    def index(self, request, *args, **kwargs):
        persons = Person.objects.select_related()
        return list_detail.object_list(
            request,
            queryset = persons,
            template_name = "person/index.html",
            paginate_by = 3,
            extra_context = {'string':'aaa'}
        )


这样就好了,继续使用类实例方法做view中,哈哈
类别:python & django | Tags: , , , , , | 0 条评论, 2078 次阅读
网友评论(0):
发表评论:

Nickname: 
Email:
Site URI: