如何使用django-rest-framework从端点检索Json元数据

时间:2018-02-07 12:29:41

标签: python django rest django-rest-framework

我使用Django rest框架从服务器检索数据。 现在我创建一个视图:

class Snipped(APIView):

    authentication_classes = (authentication.SessionAuthentication,)
    permission_classes = (permissions.AllowAny,)

    #@ensure_csrf_cookie
    def get(self, request, format=None):
        request.session["active"] = True
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return JsonResponse(serializer.data, safe=False)


    def post(self, request, format=None):

        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

模型是这样的:

# Create your models here.
class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()

    def __str__(self):
        return self.title

所以在这一点上我想知道传递给这个端点的数据的元数据,我发现http://www.django-rest-framework.org/api-guide/metadata/

但是如果发送OPTION我没有获得有关数据的信息但只有这个json回答

{
"name": "Snipped",
"description": "",
"renders": [
  "application/json",
  "text/html"
],
"parses": [
  "application/json",
  "application/x-www-form-urlencoded",
  "multipart/form-data"
],
}

没有(见http://www.django-rest-framework.org/api-guide/metadata/列表)

"parses": [
        "application/json",
        "application/x-www-form-urlencoded",
        "multipart/form-data"
    ],
    "actions": {
        "POST": {
            "note": {
                "type": "string",
                "required": false,
                "read_only": false,
                "label": "title",
                "max_length": 100
            }
        }
    }

任何想法如何用APIView实现上述结果?

1 个答案:

答案 0 :(得分:1)

仅当视图定义get_serializer时才会执行操作。

您需要定义它,以便您可以从自动模式生成中受益并返回SnippetSerializer实例。

请参阅generic views以查看实施示例。