Cache-Control 未设置响应 header

Cache-Control not being set in response header

我正在尝试通过利用浏览器缓存来优化我的 Django Web 应用程序。我在主视图函数 returned 响应中为 max-age 设置了 Cache-Control header 等于一年。然而,当我加载我的网站并检查主页上某些图像的响应 header 时,cache-control header 不存在。我尝试了两种不同的方法来设置响应 header。首先,我尝试使用 Django 内置的 cache-control 装饰器。我还尝试简单地获取呈现的响应,并在其 return 语句之前在我的视图函数中设置 header 。静态图像缓存是否不同?

查看函数

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

听起来您是在 per-view 的基础上设置 headers。但是这些视图正在处理特定的 URL,这可能不是您的静态图像文件的 URL。所以它不会对那些有任何影响。

如何为静态文件设置 headers 取决于您提供它们的方式。

  1. 最直接的解决方案是使用 whitenoise app. This serves static files from Django in the same way in both development and production, and has a setting to control the max-age.

  2. 如果您使用的是外部服务器(例如 ngnix 或 Apache),则需要对其进行配置以设置任何自定义 headers。它与 Django 没有任何关系。

  3. 如果您使用的是 Django 开发服务器,则必须 opt out 让它自动处理静态文件,而是使用设置 headers. (或者你可以在使用开发服务器时不打扰。)