【问题标题】:Django: use per-view cache in the URLconf?Django:在 URLconf 中使用按视图缓存?
【发布时间】:2015-10-20 20:11:53
【问题描述】:

我正在使用 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 文件以开始使用按视图缓存?

【问题讨论】:

    标签: python django django-1.8


    【解决方案1】:

    为此,您需要在urls.py 中导入total_spending_on_substance 视图函数,然后total_spending_on_substance 视图函数传递给cache_page 装饰器而不是字符串

    cache_page 是一个装饰器,它需要一个视图函数。因此,当您在 URLconf 中引用视图函数 total_spending_on_substance 时,请使用 cache_page 包装它。

    您可以执行以下操作:

    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'),
    

    【讨论】:

      猜你喜欢
      • 2013-08-18
      • 2013-02-01
      • 2016-07-05
      • 2023-03-21
      • 1970-01-01
      • 2012-06-09
      • 2011-01-17
      • 2013-12-07
      • 1970-01-01
      相关资源
      最近更新 更多