django中请求处理方式有2种:FBV 和 CBV

一、FBV

FBV(function base views) 就是在视图里使用函数处理请求。

看代码:

urls.py

1
2
3
4
5
6
7
8
fromdjango.conf.urlsimporturl, include
# from django.contrib import admin
frommytestimportviews
 
urlpatterns=[
# url(r‘^admin/‘, admin.site.urls),
url(r‘^index/‘, views.index),
]

views.py

1
2
3
4
5
6
7
8
9
fromdjango.shortcutsimportrender
 
 
defindex(req):
ifreq.method==‘POST‘:
print(‘methodis:‘+req.method)
elifreq.method==‘GET‘:
print(‘methodis:‘+req.method)
returnrender(req, ‘index.html‘)

注意此处定义的是函数【def index(req):】

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<form action="" method="post">
<inputtype="text"name="A"/>
<inputtype="submit"name="b"value="提交"/>
</form>
</body>
</html>

上面就是FBV的使用。

二、CBV

1、CBV(class base views) 就是在视图里使用类处理请求。

分别处理get和post请求

get和post方法是如何被调用的?????

  实际上父类View中有一个dispatch方法,作用就是通过反射来调用子类的get和post方法。

请求先走dispatch,res就是get方法或者post方法执行只有的结果

所以这个请求的过程是:请求--->dispatch--->get/post

我们现在把dispatch写到子类中,继承父类的dispatch方法。dispatch写到子类或者单独写一个类,目的是根据需求加功能。

2、我现在想实现验证登录的功能(用CBV实现登录验证不如用中间件,所以我们一般用中间件来实现验证功能)

下面的函数是实现登录的

   def dispatch(self, request, *args, **kwargs):
return super(LoginView,self).dispatch(request, *args, **kwargs) def get(self,request):
print('login')
return render(request,'login.html') def post(self,request):
# request.GET
# request.POST # 请求头中的:content-type
# 注意:request.POST中的数据是request.body中转换过来的,可能为空,因为可能转换会不成功
# request.body 但凡以post提交数据,request.body中一定有值
user = request.POST.get('user')
pwd = request.POST.get('pwd')
if user == 'alex' and pwd == "alex3714": # 生成随机字符串
# 写浏览器cookie: session_id: 随机字符串
# 写到服务端session:
# {
# "随机字符串": {'user_info':'alex}
# }
request.session['user_info'] = "alex" # 这个代码有上面注释的几个操作 return redirect('/index.html')
return render(request, 'login.html')

 
 把dispatch拿出来单独写一个类,这个类提供验证登录的功能,让其他类来继承,如下:
class AuthView(object):
def dispatch(self, request, *args, **kwargs):
if not request.session.get('user_info'):
return redirect('/login.html')
res = super(AuthView,self).dispatch(request, *args, **kwargs)
return res class IndexView(AuthView,View):
def get(self,request,*args,**kwargs):
return render(request,'index.html') def post(self,request,*args,**kwargs):
return HttpResponse('999') class OrderView(AuthView,View):
def get(self,request,*args,**kwargs):
return render(request,'index.html') def post(self,request,*args,**kwargs):
return HttpResponse('999')

  

3、对于CBV加装饰器的方法
如果加装饰器,需要导入method_decorator

加装饰的格式@method_decorator(test),test是装饰器函数

def test(func):
def inner(*args,**kwargs):
return func(*args,**kwargs)
return inner

  

 可以加在类上,但是加到类上需要指定使用的方法名
@method_decorator(test,name='get')
class LoginView(View):
 

可以加到dispatch方法,也可以加到get或post方法,不需要传name="方法名"

@method_decorator(test)
def dispath(self,request,*args,**kwargs):

  

4、特殊装饰器:CSRF Token只能加到dispatch(django的bug)

CBV的csrf装饰器需要导入

from django.views.decorators.csrf import csrf_exempt,csrf_protect
 
csrf_exempt是全局需要,唯独这个不需要
csrf_protect是全局不需要,唯独这个需要
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(LoginView,self).dispatch(request, *args, **kwargs)

  

Django【进阶】FBV 和 CBV的更多相关文章

  1. Django之FBV与CBV

    一.FBV与CBV FBV(function based views),即基于函数的视图:CBV(class based views),即基于类的视图,也是基于对象的视图.当看到这个解释时,我是很萌的 ...

  2. django的FBV和CBV

    title: python djano CBV FBV tags: python, djano, CBV, FBV grammar_cjkRuby: true --- python django的fu ...

  3. django的FBV和CBV的装饰器例子

    备忘 def auth(func): def inner(request,*args,**kwargs): u = request.COOKIES.get('username111') if not ...

  4. Django之FBV和CBV的用法

    FBV FBV,即 func base views,函数视图,在视图里使用函数处理请求. 以用户注册代码为例, 使用两个函数完成注册 初级注册代码 def register(request): &qu ...

  5. Django的FBV和CB

    Django的FBV和CBV FBV FBV(function base views) 就是在视图里使用函数处理请求. 在之前django的学习中,我们一直使用的是这种方式,所以不再赘述. CBV C ...

  6. django请求生命周期,FBV和CBV,ORM拾遗,Git

    一.django 请求生命周期 流程图: 1. 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端请求头和请求体中会包含浏览器的动作(action),这个动作通常为get或者post, ...

  7. django——FBV与CBV

    引言 FBV FBV(function base views) 就是在视图里使用函数处理请求. 在之前django的学习中,我们一直使用的是这种方式,所以不再赘述. CBV CBV(class bas ...

  8. python 全栈开发,Day84(django请求生命周期,FBV和CBV,ORM拾遗,Git)

    一.django 请求生命周期 流程图: 1. 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端请求头和请求体中会包含浏览器的动作(action),这个动作通常为get或者post, ...

  9. django基础 -- 4. 模板语言 过滤器 模板继承 FBV 和CBV 装饰器 组件

    一.语法 两种特殊符号(语法): {{ }}和 {% %} 变量相关的用{{}},逻辑相关的用{%%}. 二.变量 1. 可直接用  {{ 变量名 }} (可调用字符串, 数字 ,列表,字典,对象等) ...

随机推荐

  1. 「暑期训练」「Brute Force」 Multiplication Table (CFR256D2D)

    题意 给定一矩阵M" role="presentation">MM,Mij=ij" role="presentation">Mi ...

  2. 「日常训练」「小专题·USACO」 Broken Necklace(1-2)

    题意 圆形链条,打断一处可以形成一条链.问在哪个地方开始打断,能够形成最大的连续颜色(白色视作同样的颜色)? 分析 说起来很高级,但是我们实际上并不需要穷举打断的地方,只需要把串重复三回啊三回.然后从 ...

  3. CF 55D

    Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer numb ...

  4. mysql数据备份和还原

    MySQL是一个永久存储数据的数据库服务器.如果使用MySQLServer,那么需要创建数据库备份以便从崩溃中恢复.mysql提供了一个用于备份的实用程序mysqldump. 1.普通.sql文件中的 ...

  5. Java的同步容器和并发容器

    前言: 之前在介绍Java集合的时候说到,java提供的实现类很少是线程安全的.只有几个比较古老的类,比如Vector.Hashtable等是线程安全的,尤其是Hashtable,古老到连命名规范都没 ...

  6. Redis的高级应用——数据安全

    Redis的数据保存在内存中,速度十分快.这也就意味着,一个恶意破解redis数据库密码的用户,可以在一秒钟进行更多的尝试.如果用户密码级别较低或更换频率过长,就会造成致命的危害. 1.设置用户 Re ...

  7. Chrome Extension & Dark Theme

    Chrome Extension & Dark Theme https://chrome.google.com/webstore/detail/eimadpbcbfnmbkopoojfekhn ...

  8. jquery中ajax的使用(java)

    AJAX方式  js:界面 var prjContextPath='<%=request.getContextPath()%>'; $(document).ready(function() ...

  9. Hiberante可配置参数

    ###################### ### Query Language ### ###################### ## define query language consta ...

  10. P2168 [NOI2015]荷马史诗

    题目描述 追逐影子的人,自己就是影子 ——荷马 Allison 最近迷上了文学.她喜欢在一个慵懒的午后,细细地品上一杯卡布奇诺,静静地阅读她爱不释手的<荷马史诗>.但是由<奥德赛&g ...