【发布时间】:2017-09-08 01:51:21
【问题描述】:
我正在尝试通过利用浏览器缓存来优化我的 Django Web 应用程序。我在我的主视图函数返回的响应中设置了一个等于一年的 max-age 的 Cache-Control 标头。但是,当我加载我的网站并检查主页上某些图像的响应标头时,缓存控制标头不存在。我尝试了两种不同的方法来设置响应头。首先,我尝试使用 Django 内置的缓存控制装饰器。我还尝试简单地获取呈现的响应,并在其返回语句之前在我的视图函数中设置标题。静态图片的缓存方式不同吗?
查看功能
def view_home(request, page=None):
# FIND THE HOME PAGE IF WE DO NOT HAVE ONE
# IF NOT FOUND RETURN 404
if not page:
try:
page = WebPage.objects.get(template='home')
except WebPage.DoesNotExist:
raise Http404
try:
billboards = Billboard.get_published_objects()
except Exception as e:
logging.error(e)
billboards = None
project_types = ProjectType.get_published_objects()
budgets = Budget.get_published_objects()
deadlines = Deadline.get_published_objects()
contact_descriptions = ContactDescription.get_published_objects()
contact_form = ContactForm(type_list=project_types, budget_list=budgets,
deadline_list=deadlines, description_list=contact_descriptions)
context = {'page': page, 'billboards': billboards, 'contact_form': contact_form}
set_detail_context(request, context)
template = 'home.html'
# Add Cache control to response header
expiry_date = datetime.datetime.now() + datetime.timedelta(days=7)
response = render(request, template, context)
response['Cache-Control'] = 'max-age=602000'
response['Expires'] = expiry_date
return response
【问题讨论】:
-
如何提供静态图像?你在使用开发服务器吗?
-
它似乎没有在开发或生产中添加响应标头。在生产中,我相信 nginx 正在为我的静态文件提供服务。这很奇怪,因为我相信 Apache 正在为网站本身提供服务。也许当您使用网络托管服务提供商时,他们同时使用?
标签: django header response cache-control