我已按照以下文章尝试设置 Apache2 缓存,以便在带有 mod_wsgi 的 Ubuntu 12.10 上将其与 Django 一起使用。我希望 Apache 为我缓存一些请求。
http://www.howtoforge.com/caching-with-apaches-mod_cache-on-ubuntu-10.04
从文章中,我启用了模块并设置了以下 php 脚本来测试缓存。缓存工作得很好——我在 5 分钟后才得到一个新的时间戳。
vi /var/www/cachetest.php
<?php
header("Cache-Control: must-revalidate, max-age=300");
header("Vary: Accept-Encoding");
echo time()."<br>";
?>
现在在我的 django 响应中,我以相同的方式设置适当的标头后返回一个 HttpResponse 对象:
# Create a Response Object with the content to return and set it's
response = HttpResponse("%s"%(output_display))
response['Cache-Control'] = 'must-revalidate, max-age=20'
response['Vary'] = 'Accept-Encoding'
return response
Django 请求的缓存根本不起作用。我使用 Firefox 的 LiveHeaders 来检查 HTTP 响应标头。
对于上面的示例链接和 PHP 脚本,标题如下所示:
http://localhost/cachetest.php
GET /cachetest.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:19.0) Gecko/20100101 Firefox/19.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Cache-Control: max-age=0
HTTP/1.1 200 OK
Date: Sun, 10 Mar 2013 02:29:32 GMT
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: PHP/5.4.6-1ubuntu1.1
Cache-Control: must-revalidate, max-age=300
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 34
Connection: close
Content-Type: text/html
----------------------------------------------------------
对于我的 Django 请求 - 缓存不起作用,它总是强制冗长的操作来完成响应 - 就像用 F5 重新加载上面的 php 请求一样。使用 FireFox 插件,我似乎正在编写正确的标题:
http://localhost/testdjango/testdjango/
GET /testdjango/testdjango/ HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:19.0) Gecko/20100101 Firefox/19.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
HTTP/1.1 200 OK
Date: Sun, 10 Mar 2013 02:32:41 GMT
Server: Apache/2.2.22 (Ubuntu)
Vary: Accept-Encoding
Cache-Control: must-revalidate, max-age=20
Content-Encoding: gzip
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
----------------------------------------------------------
我究竟做错了什么?如何让 django 缓存像 php 脚本一样工作?谢谢!