如何在Django Rest Framework ViewSet中使用Last-Modified标头?

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

假设我遵循Django Rest Framework的ViewSet:

from django.contrib.auth import get_user_model
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response


class SubscriptionViewSet(ViewSet):
    def list(self, request):
        data = {'user_count': get_user_model().objects.count()}
        return Response(data)

如何与Django的last_modified装饰一起使用?或者如何实现这样的功能?

python django django-rest-framework
2个回答
0
投票

@jozo,

您可以查看https://github.com/jatir/django-rest-framework-last-modified django应用程序以使用Last-Modified

编辑:

你可以查看测试目录https://github.com/jatir/django-rest-framework-last-modified/blob/master/tests/views.py#L14中的示例


0
投票

我检查了@Makarand Bauskar提到的包裹。但是我不满意。它不活跃,它使用自定义方式如何工作/处理Last-Modified标头。所以我决定创建新的包django-rest-framework-condition

  1. 从Django重用实现 它将得到Django的修复 你可以像Django的docs中描述的那样使用它
  2. 同时提供@last_modified和@etag装饰器

要安装它:

pip install django-rest-framework-condition

用法:

from django.contrib.auth import get_user_model
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework_condition import last_modified


def my_last_modified(request, *args, **kwargs):
    return datetime(2019, 1, 1)


class SubscriptionViewSet(ViewSet):
    @last_modified(my_last_modified)
    def list(self, request):
        data = {'user_count': get_user_model().objects.count()}
        return Response(data)
© www.soinside.com 2019 - 2024. All rights reserved.