Loading

drf视图中调用的请求和响应类

drf视图中调用的请求和响应类

8.1 request

如果使用视图的时候使用的是drf中的视图(如:APIView),而不是django的视图(View),那么视图中调用的请求对象request不再是原来的request,下面给出示例:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status


class StudentAPIView(APIView):
    def get(self, request):
        print(f"request={request}")
        return Response({"message":"ok"}, status=status.HTTP_201_CREATED)

打印结果如下:

request=<rest_framework.request.Request: GET '/req/students/'>

接下来使用django的view:

from django.views import View
from django.http import HttpResponse


class StudentAPIView(View):
    def get(self, request):
        # print(f"data={request.data}")
        print(f"request={request}")
        return HttpResponse("OK")

打印结果如下:

request=<WSGIRequest: GET '/req/students/'>

由此可见drf和django视图中的request是不一样的,他们俩并不是一个,接下来介绍以下,drf视图中如何拿到前端提交的数据:

视图代码:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status


class StudentAPIView(APIView):
    def get(self, request):
        print(f"data={request.data}")
        return Response("OK",status=status.HTTP_201_CREATED)

前端提交数据如下:

{
    "name":"liming",
    "age":18,
    "sex":"男"
}

打印结果如下:

data={'name': 'liming', 'age': 18, 'sex': '男'}

另外如果是get请求,在网址上传递数据的话,可以用request.query_params来接受数据

视图如下:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status


class StudentAPIView(APIView):
    def get(self, request):
        print(f"data={request.query_params}")
        return Response({"message": "ok"}, status=status.HTTP_201_CREATED)

请求接口如下:

127.0.0.1:8000/req/students/?name=liming

打印结果如下:

data=<QueryDict: {'name': ['liming']}>

8.2 response

在drf视图中建议使用drf的Response来响应客户端,他会把字典自动转换为json数据,另外还带有api调试页面,效果如下:

x2TC6K.png

posted @ 2022-10-24 17:18  minqiliang  阅读(35)  评论(0编辑  收藏  举报
-->