• drf Response浅析


    响应

    Rsponse

       当一个请求完成后,我们一般都会返回drf中的Rsponse对象,那么该对象其中最重要的作用就是序列化。

       将需要返回给页面的数据进行JSON处理,除此之外还会对返回的页面等进行包装,它的内部其实也挺有趣儿的。

       下面是Rsponse的签名:

    def __init__(self, data=None, status=None,
                     template_name=None, headers=None,
                     exception=False, content_type=None):
    

       参数详解:

    参数描述
    data 返回的数据,内部会进行序列化,需传入一个字典
    status 返回的状态码,默认是200
    template_name 渲染并返回的模板
    headers 返回的响应头,可以组织一个字典往响应头中放入token信息等
    content_type 响应的编码格式,入application/json以及text/html等

       有了这些参数,我们可以这样做:

    from rest_framework.response import Response
    from rest_framework.views import APIView
    
    class Test(APIView):
        def get(self,request):
            ret_Msg = {"status":"100","message":""}  # 返回的信息
            return Response(
                data=ret_Msg,
                status=200, # 代表成功
                headers={"token":"xxxx"},
            )
    

       这样的话在postman中就能拿到返回的token

     

    返回状态码

       drf中内置了很多状态码的常量,我们在返回状态码时可以使用它们。

    # from rest_framework import status
    
    HTTP_100_CONTINUE = 100
    HTTP_101_SWITCHING_PROTOCOLS = 101
    HTTP_200_OK = 200
    HTTP_201_CREATED = 201
    HTTP_202_ACCEPTED = 202
    HTTP_203_NON_AUTHORITATIVE_INFORMATION = 203
    HTTP_204_NO_CONTENT = 204
    HTTP_205_RESET_CONTENT = 205
    HTTP_206_PARTIAL_CONTENT = 206
    HTTP_207_MULTI_STATUS = 207
    HTTP_208_ALREADY_REPORTED = 208
    HTTP_226_IM_USED = 226
    HTTP_300_MULTIPLE_CHOICES = 300
    HTTP_301_MOVED_PERMANENTLY = 301
    HTTP_302_FOUND = 302
    HTTP_303_SEE_OTHER = 303
    HTTP_304_NOT_MODIFIED = 304
    HTTP_305_USE_PROXY = 305
    HTTP_306_RESERVED = 306
    HTTP_307_TEMPORARY_REDIRECT = 307
    HTTP_308_PERMANENT_REDIRECT = 308
    HTTP_400_BAD_REQUEST = 400
    HTTP_401_UNAUTHORIZED = 401
    HTTP_402_PAYMENT_REQUIRED = 402
    HTTP_403_FORBIDDEN = 403
    HTTP_404_NOT_FOUND = 404
    HTTP_405_METHOD_NOT_ALLOWED = 405
    HTTP_406_NOT_ACCEPTABLE = 406
    HTTP_407_PROXY_AUTHENTICATION_REQUIRED = 407
    HTTP_408_REQUEST_TIMEOUT = 408
    HTTP_409_CONFLICT = 409
    HTTP_410_GONE = 410
    HTTP_411_LENGTH_REQUIRED = 411
    HTTP_412_PRECONDITION_FAILED = 412
    HTTP_413_REQUEST_ENTITY_TOO_LARGE = 413
    HTTP_414_REQUEST_URI_TOO_LONG = 414
    HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415
    HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE = 416
    HTTP_417_EXPECTATION_FAILED = 417
    HTTP_418_IM_A_TEAPOT = 418
    HTTP_422_UNPROCESSABLE_ENTITY = 422
    HTTP_423_LOCKED = 423
    HTTP_424_FAILED_DEPENDENCY = 424
    HTTP_426_UPGRADE_REQUIRED = 426
    HTTP_428_PRECONDITION_REQUIRED = 428
    HTTP_429_TOO_MANY_REQUESTS = 429
    HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431
    HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS = 451
    HTTP_500_INTERNAL_SERVER_ERROR = 500
    HTTP_501_NOT_IMPLEMENTED = 501
    HTTP_502_BAD_GATEWAY = 502
    HTTP_503_SERVICE_UNAVAILABLE = 503
    HTTP_504_GATEWAY_TIMEOUT = 504
    HTTP_505_HTTP_VERSION_NOT_SUPPORTED = 505
    HTTP_506_VARIANT_ALSO_NEGOTIATES = 506
    HTTP_507_INSUFFICIENT_STORAGE = 507
    HTTP_508_LOOP_DETECTED = 508
    HTTP_509_BANDWIDTH_LIMIT_EXCEEDED = 509
    HTTP_510_NOT_EXTENDED = 510
    HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511
    
    

    配置Rsponse

       如果你在浏览器中访问该页面,可以发现它返回的其实是一个页面:

       但是在postman中,返回的则是json格式的字符串。

    {
        "status": "100",
        "message": ""
    }
    

       原因是因为它会根据request对象中的请求头accept来自动转换对应的数据格式,如果前端请求中未进行Accept声明,则会采用默认方式处理响应数据,我们可以通过配置来修改默认响应格式。

       可以在rest_framework.settings查找所有的drf默认配置项

    DEFAULTS = {
    
        'DEFAULT_RENDERER_CLASSES': [
            'rest_framework.renderers.JSONRenderer',   # 返回json
            'rest_framework.renderers.BrowsableAPIRenderer',  # 返回页面
        ],
        
        }
    

       如果我们想让浏览器访问页面时也返回JSON格式,则可以进行下面两种配置方法。

    局部配置

       只指定某一个视图返回规定的数据格式:

    from rest_framework.response import Response
    from rest_framework.views import APIView
    from rest_framework import settings
    from rest_framework.renderers import JSONRenderer
    
    class Test(APIView):
        renderer_classes=[JSONRenderer,]  # 该视图只返回JSON数据
        def get(self,request):
            ret_Msg = {"status":"100","message":""}  # 返回的信息
            return Response(
                data=ret_Msg,
                status=200, # 代表成功
                headers={"token":"xxxx"},
            )
    

    全局配置

       由于它返回时查找顺序是先找局部,再找Django.settings.py,最后再找rest_framework.settings.py,所以我们可以再Django.settings.py下进行覆写:

    DEFAULTS = {
        'DEFAULT_RENDERER_CLASSES': [
            'rest_framework.renderers.JSONRenderer',   # 所有视图均返回JSON格式数据
        ],
        }
    
  • 相关阅读:
    英国下院通过法案允许合成人兽胚胎
    老外关于思考时间的问与答
    性能测试中用LambdaProbe监控Tomcat
    BT下载原理
    汽车维修行业呼吁大学生加入修车行列
    一个女研究生(高级测试工程师)的职业选择
    微软称20日验证Windows与Office 盗版将黑屏 网友评论
    Xbox摇身变NAS:BT的使用问题与性能测试
    李开复建言大学生:求职中不要把钱看得太重
    IBM雇员将罢工15分钟 为抗议公司裁员
  • 原文地址:https://www.cnblogs.com/Yunya-Cnblogs/p/13874273.html
Copyright © 2020-2023  润新知