1、请求和响应
1、文档
https://www.django-rest-framework.org/tutorial/2-requests-and-responses/
https://q1mi.github.io/Django-REST-framework-documentation/tutorial/2-requests-and-responses_zh/
2、请求对象:request.data
# request.data # 处理任意数据 适用于‘POST‘,‘PUT‘和‘PATCH‘方法
# request.data可以处理传入的json请求,但它也可以处理其他格式。
3、返回对象:Response
# return Response(data) 渲染成客户端请求的内容类型。
4、status code
from rest_framework import status # status模块中的每个状态代码
return Response(status=status.HTTP_404_NOT_FOUND)
5、API views
# 基于函数视图, 编写API视图的包装器 等价于 基于类视图的APIView类
@api_view([‘GET‘, ‘POST‘])
@api_view([‘GET‘, ‘PUT‘, ‘DELETE‘])
REST框架提供了两个可用于编写API视图的包装器(wrappers)。
- 用于基于函数视图的
@api_view
装饰器。 - 用于基于类视图的
APIView
类。
6、可选格式后缀
视图中
def snippet_detail(request, pk, format=None)
def snippet_list(request, format=None)
urls
from rest_framework.urlpatterns import format_suffix_patterns # 可选的格式后缀
urlpatterns = format_suffix_patterns(urlpatterns)
7、代码
# ## Tutorial 2: Requests and Responses from rest_framework import status # status模块中的每个状态代码 from rest_framework.decorators import api_view from rest_framework.response import Response from snippets.models import Snippet from snippets.serializers import SnippetSerializer @api_view([‘GET‘, ‘POST‘]) # 基于函数视图, 编写API视图的包装器 等价于 基于类视图的APIView类 def snippet_list(request, format=None): # 可选的格式后缀 """ 列出所有的snippets,或者创建一个新的snippet。 """ if request.method == ‘GET‘: snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data) # return Response(data) 渲染成客户端请求的内容类型。 elif request.method == ‘POST‘: serializer = SnippetSerializer(data=request.data) # request.data # 处理任意数据 适用于‘POST‘,‘PUT‘和‘PATCH‘方法 if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) # status模块中的每个状态代码 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view([‘GET‘, ‘PUT‘, ‘DELETE‘]) def snippet_detail(request, pk, format=None): # 可选的格式后缀 """ 获取,更新或删除一个snippet实例。 """ try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == ‘GET‘: serializer = SnippetSerializer(snippet) return Response(serializer.data, status=status.HTTP_200_OK) elif request.method == ‘POST‘: serializer = SnippetSerializer(snippet, data=request.data) # request.data可以处理传入的json请求,但它也可以处理其他格式。 if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == ‘DELETE‘: snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)
8、效果
http http://127.0.0.1:8000/snippets/ Accept:application/json # 请求JSON
http http://127.0.0.1:8000/snippets.json # JSON后缀
# POST表单数据
http --form POST http://127.0.0.1:8000/snippets/ code="print 123"
原文地址:https://www.cnblogs.com/venicid/p/12009928.html
时间: 2024-11-13 08:59:49