第二章 restframework——框架安装与APIView
一、restframework框架安装
二、Django的CBV源码分析
三、APIView介绍
四、django中的request
五、restframework中的request
一、restframework框架安装
方式一:pip3 install djangorestframework
方式二:pycharm图形化界面安装
方式三:pycharm命令行下安装(装在当前工程所用的解释器下)
切记去项目settings.py配置中配置restframework
否则会报如下错误
二、Django的CBV源码分析
CBV(class base view):基于类的view,就叫CBV
Python是一个面向对象的编程语言,如果只用函数来开发,有很多面向对象的优点就错失了(继承、封装、多态)。所以Django在后来加入了Class-Based-View。可以让我们用类写View。这样做的优点主要下面两种:
- 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
- 可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性
使用步骤:
①使用前切记导入View,将创建的类继承自View
from django.views import View
②该类会自动根据post请求与get请求自动分辨请求类型,选择对应的函数def get()或者def post()
③dispatch类似装饰器,可以在def get()或者def post()前后添加代码
记得继承类obj=super().dispatch(request, *args, **kwargs),在其前后添加代码
④在路由调用视图函数时记得调用as_view()方法
from django.views import View
class AddPublish(View):
def dispatch(self, request, *args, **kwargs):
print(request)
print(args)
print(kwargs)
# 可以写类似装饰器的东西,在前后加代码
obj=super().dispatch(request, *args, **kwargs)
return obj
def get(self,request):
return render(request,'index.html')
def post(self,request):
request
return HttpResponse('post')
源码分析(右击新标签中打开图片可以看的清楚些)
使用装饰器装饰CBV(dispatch)
类中的方法与独立函数不完全相同,因此不能直接将函数装饰器应用于类中的方法 ,我们需要先将其转换为方法装饰器。
Django中提供了method_decorator装饰器用于将函数装饰器转换为方法装饰器。
# 使用CBV时要注意,请求过来后会先执行dispatch()这个方法,如果需要批量对具体的请求处理方法,如get,post等做一些操作的时候,这里我们可以手动改写dispatch方法,
这个dispatch方法就和在FBV上加装饰器的效果一样。
class Login(View):
def dispatch(self, request, *args, **kwargs):
print('before')
obj = super(Login,self).dispatch(request, *args, **kwargs)
print('after')
return obj
def get(self,request):
return render(request,'login.html')
def post(self,request):
print(request.POST.get('user'))
return HttpResponse('Login.post')
三、APIView介绍
使用步骤:
①导入模块
from rest_framework.views import APIView
②使CBV继承自restframework中的APIView而非django的View
上文分析了django中的as_view方法,让我们看看APIView中的as_view()
@classmethod def as_view(cls, **initkwargs): """ Store the original class on the view function. This allows us to discover information about the view when we do URL reverse lookups. Used for breadcrumb generation. """ if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet): def force_evaluation(): raise RuntimeError( 'Do not evaluate the `.queryset` attribute directly, ' 'as the result will be cached and reused between requests. ' 'Use `.all()` or call `.get_queryset()` instead.' ) cls.queryset._fetch_all = force_evaluation view = super(APIView, cls).as_view(**initkwargs) view.cls = cls view.initkwargs = initkwargs # Note: session based authentication is explicitly CSRF validated, # all other authentication is CSRF exempt. return csrf_exempt(view)