【问题标题】:Pre cache django REST views预缓存 Django REST 视图
【发布时间】:2012-04-24 22:30:41
【问题描述】:

我有一个用 django 实现的 REST-ful 服务,对于访问的每个资源,我想缓存可能被访问的相关数据。

例如 ressource http://www.example.com/publication/1280 会给出 xml 响应:

<publication xmlns="http://www.example.com" xmlns:atom="http://www.w3.org/2005/atom">
<abstract>None</abstract>
<owner>
    <atom:link rel="owner" type="application/xml" href="http://www.example.com/user/1">ckpuser</atom:link>
</owner>
<authors>
<author>
   <atom:link rel="author" type="application/xml" href="http://www.example.com/author/564">P. Almquist</atom:link>
</author>
</authors>
<comments></comments>
<tags></tags>
<keywords></keywords>
<referencematerials></referencematerials>
<peerreviews></peerreviews>
<fields>
<howpublished>RFC 1349 (Proposed Standard)</howpublished>
<url>http://www.ietf.org/rfc/rfc1349.txt</url>
</fields>
</publication>

然后我想预缓存与资源http://www.example.com/user/1http://www.example.com/author/564 关联的数据。

在 Web 服务中,给出的响应是一种数据结构,我认为缓存整个响应比查询集更好。如果我们缓存查询集,那么每次访问资源时我们都会在模板渲染上浪费时间。

这是一个好方法吗?我错过了什么吗?

如果这种方法是正确的,那么我如何使用 django 提供的中间件预先缓存视图

'django.middleware.cache.UpdateCacheMiddleware'

'django.middleware.cache.FetchFromCacheMiddleware'?

谢谢

【问题讨论】:

    标签: django web-services rest django-views django-cache


    【解决方案1】:

    试试 Django 的per-view cache

    基本上,它使用 URL(和其他一些东西)作为缓存键,实现如下:

    from django.views.decorators.cache import cache_page
    
    @cache_page(60 * 15) # cache for 15 minutes
    def my_view(request):
    ...
    

    这将缓存视图的 XML 输出,您怀疑在缓存有效时检索它所需的资源比仅缓存查询集要少。

    缓存中间件django.middleware.cache.UpdateCacheMiddlewaredjango.middleware.cache.FetchFromCacheMiddleware 将缓存整个站点,这很可能不是您想要的。

    【讨论】:

      猜你喜欢
      • 2013-08-18
      • 2012-03-10
      • 2011-09-26
      • 1970-01-01
      • 2013-12-07
      • 2021-10-26
      • 2016-02-23
      • 2017-03-12
      • 1970-01-01
      相关资源
      最近更新 更多