1. 主页
  2. DRF实战教程
  3. DRF实战之请求和响应

DRF实战之请求和响应

请求

REST里面有个HttpRequest特别相似的对象叫request,主要获取前端传递过来的数据,获取数据的方法就是request.data。

响应

REST里面有个HttpResponse特别相似的对象叫Response,主要用来给前端传递数据,传递数据的方法就是Response(data)。

状态码

REST里面的状态码比较人性化。每个状态都用意思去表示。比如

​HTTP_200_OK = 200 #OK
HTTP_201_CREATED = 201 #创建成功
HTTP_403_FORBIDDEN = 403 # 权限拒绝

API视图

API视图主要为了咱们RESTFUL风格的API。主要用来包装request,response、现在api请求方法。

  • 基于函数视图的@api_view装饰器
  • 基于类视图的APIView

综合用法

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

@api_view(['GET', 'POST'])
def user_list(request):
    if request.method == 'GET':
        users = User.objects.all()
        serializer = UserSerializer(users, many=True, context={'request': request})
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = UserSerializer(data=request.data, context={'request': request})
        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)

类视图

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.http import Http404

class UserDetail(APIView):
    def get_user(self, id):
        try:
            user = User.objects.get(id=id)
            return user
        except User.DoesNotExist:
            raise Http404

    def get(self, request, *args, **kwargs):
        user = self.get_user(kwargs.get('id'))
        serializer = UserSerializer(user, context={'request': request})
        return Response(serializer.data)

    def put(self, request, *args, **kwargs):
        user = self.get_user(kwargs.get('id'))
        serializer = UserSerializer(user, data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def detete(self, request, *args, **kwargs):
        user = self.get_user(kwargs.get('id'))
        user.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

类视图取消csrf

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt,name='dispatch')
class xxx(APIView)

给api加后缀

from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
    path('users/', views.user_list, name='user_list'),  # 获取或创建
    # path('users/<int:id>/', views.user_detail, name='user-detail'),  # 查找、更新、删除
    path('users/<int:id>/', views.UserDetail.as_view(), name='user-detail'),  # 查找、更新、删除
]

from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api'])

在视图方法里面加个format参数

def put(self, request, format=None, *args, **kwargs):
    user = self.get_user(kwargs.get('id'))
    serializer = UserSerializer(user, data=request.data, context={'request': request})
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我们要如何帮助您?

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注