django rest framework http status code

发布时间:2020-01-13 14:46:53编辑:Run阅读(4236)

    判断请求是否成功,可以从返回的状态码来区别,所以当写接口的时候也要这样做,标准化.

    from rest_framework import status通过导入status,里面已经定义好了状态码,源码如下:

    """
    Descriptive HTTP status codes, for code readability.
    
    See RFC 2616 - https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
    And RFC 6585 - https://tools.ietf.org/html/rfc6585
    And RFC 4918 - https://tools.ietf.org/html/rfc4918
    """
    from __future__ import unicode_literals
    
    
    def is_informational(code):
        return 100 <= code <= 199
    
    
    def is_success(code):
        return 200 <= code <= 299
    
    
    def is_redirect(code):
        return 300 <= code <= 399
    
    
    def is_client_error(code):
        return 400 <= code <= 499
    
    
    def is_server_error(code):
        return 500 <= code <= 599
    
    
    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_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_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_422_UNPROCESSABLE_ENTITY = 422
    HTTP_423_LOCKED = 423
    HTTP_424_FAILED_DEPENDENCY = 424
    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_507_INSUFFICIENT_STORAGE = 507
    HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511


    django rest framework 已经封装好了接口的类,通过导入from rest_framework.views import APIView,继承APIView类,APIView类会自动判断请求的方式,通过不同的请求(get,post)触发不同的方法,代码如下:

    from rest_framework.views import APIView
    from django.http import JsonResponse
    from rest_framework import status
    import hashlib
    import base64
    
    
    class CeShi(APIView):
        def dispatch(self, request, *args, **kwargs):
            """
            请求到来之后,都要执行dispatch方法,dispatch方法根据请求方式不同触发 get/post/方法
            """
            return super().dispatch(request, *args, **kwargs)
    
        def get(self, request):
            # get 请求
            key = self.get_token()
            token = request.GET.get('token')
            print(key)
            if key != token:
                return JsonResponse({'status': status.HTTP_401_UNAUTHORIZED, 'msg': 'Token error'}, status=status.HTTP_401_UNAUTHORIZED)
            return JsonResponse({'status': status.HTTP_200_OK, 'data': []}, status=status.HTTP_200_OK)
    
        def post(self, request):
            token = request.data.get('token')
            key = self.get_token()
            print(request.data)
            # 判断token是否正确
            if key != token:
                return JsonResponse({'status': status.HTTP_401_UNAUTHORIZED, 'msg': 'Token error'}, status=status.HTTP_401_UNAUTHORIZED)
            return JsonResponse({'status': status.HTTP_200_OK, 'data': []}, status=status.HTTP_200_OK)
    
        def get_token(self):
            """
            sha256+base64得到token
            :return: token
            """
            appkey = 'helloworld'
            # sha256加密
            s = hashlib.sha256(appkey.encode("utf-8")).hexdigest()
            # base64编码
            token = base64.b64encode(s.encode("utf-8")).decode('utf-8')
            return token


    postman截图效果: 可以看到http请求的状态码变成401,验证错误!

    image.png


    请求成功截图: 请求状态码200

    image.png


关键字