gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:11:31 25 4
gpt4 key购买 nike

我正在使用 Django Rest 框架从服务器检索数据。现在我创建一个 View :

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/

但是如果发送选项,我不会获取有关数据的信息,而只会获取此 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 实现上述结果吗?

最佳答案

仅当 View 定义 get_serializer 时,操作才会起作用。 .

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

引用generic views查看实现示例。

关于python - 如何使用 django-rest-framework 从端点检索 Json 元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48663854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com