day71作业
总路由urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.urls'))
]
分发路由urls.py
from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^books/$', views.BookView.as_view()),
url(r'^books/(?P<pk>\d+)/$', views.BookView.as_view())
]
settings配置
# 先注册'rest_framework'
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
],
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
],
'EXCEPTION_HANDLER': 'api.exception.exception_handler',
}
视图views.py
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.renderers import BrowsableAPIRenderer, JSONRenderer
from rest_framework.parsers import JSONParser, FormParser, MultiPartParser
class BookView(APIView):
# 配置局部渲染类
RENDERER_CLASSES = [BrowsableAPIRenderer, JSONRenderer]
# 局部配置解析类
PARSER_CLASSES = [JSONParser, FormParser, MultiPartParser]
def get(self, request, *args, **kwargs):
return Response(
data={
'msg': 'view get ok'
}
)
处理响应 服务端异常处理
# 应用下建立 exception, 重写exception_handler方法
from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler
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