来自 Wagtail API 的结果是否可以缓存或设置 `Cache-Control` header?

Can the results from the Wagtail API be cached or have a `Cache-Control` header set?

我正在尝试缓存来自 Wagtail 的 API 视图之一。我已经搜索了缓存 Django REST 的方法,并找到了一种通过在响应中注入 Cache-Control 的方法。 如此处所示:http://www.django-rest-framework.org/api-guide/responses/#standard-httpresponse-attributes

此方法不适用于 Wagtail,因为序列化器是 Wagtail 的一部分。我有办法做到这一点吗?

Wagtail API 端点在 wagtail.api.v2.endpoints (and other locations such as wagtail.images.api.v2.endpoints 中定义,可以进行子类化以提供自定义行为,例如在响应中设置额外的 header。例如,要将 Cache-Control header 添加到 PagesAPIEndpoint 的详细视图:

from wagtail.api.v2.endpoints import PagesAPIEndpoint

class CachedPagesAPIEndpoint(PagesAPIEndpoint):
    def detail_view(self, request, pk):
        response = super().detail_view(request, pk)
        response['Cache-Control'] = 'no-cache'
        return response

然后,in your api.py,注册您的自定义 CachedPagesAPIEndpoint 以代替标准 PagesAPIEndpoint