Django中如何对TemplateView进行缓存

问题来源

在使用Django的Cache模块进行页面缓存

代码如下:

class Detail(TemplateView):

    @cache_page(60 * 10)
    def get(self, request, *args, **kwargs):
        ...

运行代码,提示错误信息如下:

AttributeError at /www_cmypsc_com/detail-127.html
'Detail' object has no attribute 'method'
Request Method: GET
Request URL:    ***
Django Version: 2.1.5
Exception Type: AttributeError
Exception Value:    
'Detail' object has no attribute 'method'
Exception Location: /usr/local/lib/python3.6/dist-packages/django/middleware/cache.py in process_request, line 132
Python Executable:  /usr/bin/python3.6
Python Version: 3.6.7
Python Path:    
['/opt/prod/sites',
 '/usr/local/bin',
 '/usr/lib/python36.zip',
 '/usr/lib/python3.6',
 '/usr/lib/python3.6/lib-dynload',
 '/usr/local/lib/python3.6/dist-packages',
 '/usr/lib/python3/dist-packages']
Server time:    Thu, 26 Sep 2019 16:22:11 +0800

TemplateView进行缓存异常

解决办法

我们可以在url的配置中进行缓存,来规避这个问题

from django.views.decorators.cache import cache_page


from . import views

urlpatterns = [
    url('^/detail-(?P<pk>\d+).html', cache_page(60*60)(views.Detail.as_view())),
]