Djangorestfromwork job 1

operation

Simple flow through a request source through the module, establishing a view class, complete parsing module and a rendering module configured global local

url configuration

urlpatterns = [

    url(r'^v2/cars/$',views.CarAPIView.as_view()),
    url(r'^v2/cars/(?P<pk>\d+)/$',views.CarAPIView.as_view()),

]

Configuration settings

REST_FRAMEWORK = {
    # 解析模块:
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.FormParser',    # urlencoded数据格式
        'rest_framework.parsers.MultiPartParser'    # form-data数据格式
    ],
    # 如果把 其中某一个参数注释掉之后,则会出现客户端发过来的参数解析不了
# {
#     "detail": "<api.views.CarAPIView object at 0x000000000BC29E48> - GET - 不支持请求中的媒体类型 “application/json”。"
# }

    # 渲染模块
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',  # 项目真正上线的时候会把它注释掉,因为浏览器访问接口是一个页面
    ],
    # 异常模块处理
    # 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler',    django中提供的
    'EXCEPTION_HANDLER': 'api.exception.exception_handler',
}

Exception handling module

# 一定要在settings文件中将异常模块配置自己的异常处理函数
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.response import Response

def exception_handler(exc, context):
    response = drf_exception_handler(exc, context)
    detail = '%s - %s - %s' % (context.get('view'), context.get('request').method, exc)
    if not response:  # 服务端错误
        response =  Response({'detail': detail})
    else:
        response.data = {'detail': detail}

    # 核心:线上要将response.data.get('detail')信息记录到日志文件
    # logger.waring(response.data.get('detail'))

    return response

View layer disposed views

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

class CarAPIView(APIView):
    def get(self,request,*args,**kwargs):
        print(request.method)
        print(request._request.method)
        return Response(data={"msg":"apiview get ok"},status=200)

    def post(self,request,*args,**kwargs):
        return Response({
            "msg":"apiview post ok"
        })

Second package Response class (class inheritance Custom Response APIResponse a), to optimize the response
right: APIResponse ( 'results' = [ ]) # status data and status code information has a default value, may not pass
exception: Response (1, 'error', status = 400) # information can, can have an error code provided by the network status bit status code transmitted data and state
in response to results of the previous response of the encapsulated package is consistent, but the response is greatly simplified wording:

class APIResponse(Response):
    # 重写的APIResponse类是继承了restframework中的Response  再此基础上重写多个初始化值
    # 设置默认参数
    def __init__(self, data_status=0, data_msg='ok', results=None, http_status=None, headers=None, exception=False, **kwargs):
        data = {
            'status': data_status,
            'msg': data_msg,
        }
        # results可能是False、0等数据,这些数据某些情况下也会作为合法数据返回
        if results is not None:
            data['results'] = results
        data.update(kwargs)
        # 继承并重用父类的 的init方法,把自定义的data数据体传进去
        # 父类的:__init__(self, data=None, status=None,template_name=None, headers=None,exception=False, content_type=None):
        # 异常响应,默认为False
        super().__init__(data=data, status=http_status, headers=headers, exception=exception)

class CarAPIView(APIView):
    def get(self,request,*args,**kwargs):
        print(request.query_params)
        print(request.data)
        # print(request.method)
        # print(request._request.method)
        return APIResponse(data={"msg":"apiview get ok"})

Guess you like

Origin www.cnblogs.com/ghylpb/p/12154367.html