Django:在URLconf中使用per-view缓存?

时间:2015-07-29 17:34:14

标签: python django django-1.8

我正在使用Django 1.8,我想开始使用Django的文件系统缓存,a per-view cache in the URLconf

这是我的urls.py

urlpatterns = patterns(
  '',
  url(r'^api/1.0/spending$',
      'frontend.views.views_api_spending.total_spending_on_substance',
      name='total_spending'),

这就是我正在尝试的:

urlpatterns = patterns(
  '',
  url(r'^api/1.0/spending$',
      cache_page(60 * 15)('frontend.views.views_api_spending.total_spending_on_substance'),
      name='total_spending'),

但我收到一个错误:TypeError at /api/1.0/spending: 'str' object is not callable

如果我删除了引号,我会得到:NameError at /api/1.0/spending: name 'frontend' is not defined

如何调整我的urls文件以开始使用每个视图缓存?

1 个答案:

答案 0 :(得分:0)

为此,您需要在total_spending_on_substance中导入urls.py视图功能,然后total_spending_on_substance视图功能传递给cache_page装饰器而不是字符串< /强>

cache_page是一个装饰器,它需要一个视图功能。因此,当你在URLconf中引用它时,用view_page包装视图函数total_spending_on_substance

您可以执行以下操作:

from frontend.views.views_api_spending import total_spending_on_substance # import the view function

urlpatterns = patterns(
  '',
  url(r'^api/1.0/spending$',
      cache_page(60 * 15)(total_spending_on_substance), # pass function instead of string
      name='total_spending'),