url配置
urlpatterns = [
url(r'^cars/$',views.CarAPIView.as_view()),
url(r'^cars/(?P<pk>d+)/$',views.CarAPIView.as_view()),
]
settings配置
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
],
'EXCEPTION_HANDLER': 'api.exception.exception_handler',
}
异常处理模块
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}
return response
视图层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"
})
class APIResponse(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,
}
if results is not None:
data['results'] = results
data.update(kwargs)
super().init(data=data, status=http_status, headers=headers, exception=exception)
class CarAPIView(APIView):
def get(self,request,*args,**kwargs):
return APIResponse(data={"msg":"apiview get ok"})