如何在Django中设置http响应的过期日期?

问题描述 投票:1回答:2

我如何在Django中正确设置我的http响应现在+ 1年有效期?我可以使用render()快捷方式吗?

django cache-control
2个回答
2
投票

您可以使用装饰器完成此操作,请参阅有关使用per-view cache的文档。


1
投票

[另一种选择是使用patch_response_headers(response, cache_timeout=None)中的django.utils.cache。这将根据指定的超时时间(以秒为单位)简单地在Expires对象上设置Cache-Controlresponse HTTP标头。

例如,在您的视图代码中,可以在将其返回之前将其应用于HttpResponse对象:

from django.utils.cache import patch_response_headers

# Add Expires and Cache-Control headers to cache in browser for 5 minutes
patch_response_headers(response, cache_timeout=300)

return response

如果您只希望浏览器将响应缓存特定的时间,而服务器上没有任何缓存,则这可能是一个更好的解决方案。

请参阅Django文档以了解更多详细信息:https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.cache.patch_response_headers

© www.soinside.com 2019 - 2024. All rights reserved.