A作业(必做)
"""
1、整理今天所学知识点
2、简单过过请求模块的源码流程,建立一个视图类,完成一项渲染模块与解析模块的全局局部配置
3、在自己项目中自定义一下异常处理函数,并配置给项目
"""
from rest_framework.parsers import JSONParser,FormParser,MultiPartParser
from rest_framework.renderers import JSONRenderer
from rest_framework.renderers import BrowsableAPIRenderer
from rest_framework.views import APIView
from rest_framework.response import Response
class Student(APIView):
parser_classes = [JSONParseer]
renderer_classes = [JSONRenderer]
def get(self,request,*args,**kwargs):
return Response('drf get ok')
def post(self,request,*args,**kwargs):
return Response('drf post ok')
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.response import Response
from rest_framework import status
def exception_handler(exc, context):
response = drf_exception_handler(exc, context)
detail = '%s-%s-%s' %(context.get('view'),context.get('request'),exc)
if not response:
response = Response({'detail':detail},, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
else:
response.data = {'detail':detail}
return response
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')),
]
api.urls.py:
from django.conf.urls import url
from . import views
urlpatterns = {
url(r'^student/$',views.Student.as_view()),
}
B作业(选做)
"""
1、预习视频
2、后期项目会出现大量的响应,响应数据可以如下
正确的:Response({'status':0,'msg':'ok','results':[]})
异常的:Response({'status':1,'msg':'error'}, status=400)
...
能不能二次封装Response类(自定义一个APIResponse类继承Response),优化响应
正确的:APIResponse('results'=[]) # 数据状态码和状态信息有默认值,可以不传
异常的:Response(1,'error', status=400) # 可以按位传数据状态码和状态信息,错误时还可以设置网络状态码
封装后的响应与封装前的响应结果一致,但是大大简化了响应写法
"""