APIView

一、FBV和CBV


FBV(function based view)基于函数的视图控制

实例一: 1.在url映射表注册新的映射关系: `url('^login/',view.index)` index是个函数变量,指向函数的内存空间,用户一旦访问正则表达式字符串^index/,视图函数就会 被执行,传一个固定参数request,它是django在wsgiref中封装的request对象 2.在views.py中自定义注册函数 ``` def login_view(self, request): user = request.POST.get("user") pwd = request.POST.get("pwd") queryset=User.objects.filter(user=user,pwd=pwd) if queryset: return HttpResponse("OK") else: return HttpResponse("ERROR") ```

CBV(class based view)基于类的视图控制

实例一: 1.在urls.py的映射表中注册映射关系 `url('^login/',views.LoginView.as_view()),`

2.在views.py中

from django.views import View
class LoginView(View):
    def get(self, request):
        return render(request, "login.html")

    def post(self, request):
        if request.method == "POST":
            user = request.POST.get("user")
            pwd = request.POST.get("pwd")
        return HttpResponse("ok")

查看CBV源码:

在urls.py的映射表中注册映射关系
url('^login/',views.LoginView.as_view()), views.LoginView对应的是该应用下的views文件里的
LoginView类不是类的实例,该类继承了from django.views import View的View。而LoginView.as_view()是
在LoginView类找这个类方法,在里面没找到就去LoginView类的父类View里面去找。

	url(r'^login/', views.LoginView.as_view()),
	||
	url(r'^login/', View.as_view()),

在父类View里找到
http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
这是其父类View支持的http方法

    @classonlymethod
    def as_view(cls, **initkwargs):
	  for key in initkwargs:
		if key in cls.http_method_names:
			raise TypeError("xxxxx")
		if not hasattr(cls, key):
			raise TypeError("xxxxx")
	def view(request, *args, **kwargs):
		return self.dispatch(request, *args, **kwargs)
	return view  #返回一个函数变量。

这样,我们就可以将

	url('^login/',views.LoginView.as_view())
		||
	url(r'^login/', View.as_view()),
		||
	url(r'^login/', View.view),

因为我们还没看到response,就接着到self.dispatch(request, *args, **kwargs)里看里面有没有response。

def dispatch(self, request, *args, **kwargs):
	if request.method.lower() in self.http_method_names:
        	handler = getattr(self, request.method.lower())
        return handler(request, *args, **kwargs)#执行我们自己的定义的方法。

类有实例方法和类方法

django序列化接口


from app02.models import *
from django.shortcuts import render, HttpResponse
from django.core.serializers import serialize

class UserView(View):
    def get(self, request):
        queryset = User.objects.all()
        queryset = serialize("json", queryset)
        return HttpResponse(queryset)

    def post(self, request):
        pass

RESTful的APIView


下载:

清华源:pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple djangorestframework
pip包管理工具:pip3 install djangorestframework

使用:

1.先注册app
2.url注册:url(r'^user/', v2.UserView.as_view())
3.在视图控制中

from rest_framework.views import APIView
class UserView(APIView):
    def get(self, request):
        queryset = User.objects.all()
        queryset = serialize("json", queryset)
        return HttpResponse(queryset)

    def post(self, request):
        pass

看源码

*** 1.在 urls.py映射表中注册url `url(r'^user/', v2.UserView.as_view())` 2.v2.UserView是一个应用下的自定义类,该类继承了rest_framework.views的APIView, 当我们到APIView可以看见其继承了django.views的View。那么我们v2.UserView.as_view() 的as_view()类方法是谁的? 是rest_framework.views的APIView内的类方法。 ``` @classmethod def as_view(cls, **initkwargs): view = super(APIView, cls).as_view(**initkwargs)#继承了django.views.View的as_view() ``` 在django.views.View的as_view()里遇到 ``` def view(request, *args, **kwargs): return self.dispatch(request, *args, **kwargs) ``` 要用self.dispatch(request, *args, **kwargs),先看self,这里的self是我们自定义的类UserView,在 这里找有没有dispatch(request, *args, **kwargs),没有就找rest_framework.views.APIView里找, 找到了 ``` def dispatch(self, request, *args, **kwargs): if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower()) response = handler(request, *args, **kwargs) return response ``` ![](https://images2018.cnblogs.com/blog/1326778/201808/1326778-20180803211032308-1411029640.png)
posted @ 2018-07-31 15:16  桥前石头  阅读(154)  评论(0编辑  收藏  举报