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. Python 3基础教程28-内置函数

    本文介绍Python中的内置函数,Python中有很多内置的,功能强大的函数,可以帮我们解决很多问题,有些方法,根本不需要你去再次编写实现函数,你直接调用就可以.在这之前,需要介绍下,如何在windo ...

  2. 修改有数据oracle字段类型 从number转为varchar

    --修改有数据oracle字段类型 从number转为varchar--例:修改ta_sp_org_invoice表中RESCUE_PHONE字段类型,从number转为varchar --step1 ...

  3. Python 中的容器 collections

    写在之前 我们都知道 Python 中内置了许多标准的数据结构,比如列表,元组,字典等.与此同时标准库还提供了一些额外的数据结构,我们可以基于它们创建所需的新数据结构. Python 附带了一个「容器 ...

  4. The Erdös-Straus Conjecture 题解

    题面 Description The Brocard Erdös-Straus conjecture is that for any integern > 2 , there are posit ...

  5. 机器学习 (三) 逻辑回归 Logistic Regression

    文章内容均来自斯坦福大学的Andrew Ng教授讲解的Machine Learning课程,本文是针对该课程的个人学习笔记,如有疏漏,请以原课程所讲述内容为准.感谢博主Rachel Zhang 的个人 ...

  6. C#中async和await用法

    .net 4.5中新增了async和await这一对用于异步编程的关键字. async放在方法中存在await代码的方法中,await放在调用返回Task的方法前. class Class1 { pr ...

  7. iOS-显示日期的转换,今天,昨天,前天

    + (NSString *)stringWithDate:(NSDate *)date{ // 1.获得年月日 NSCalendar *calendar = [NSCalendar currentCa ...

  8. 【bzoj5060】魔方国 乱搞+特判

    题目描述 一张未知的有重边无自环的图,只知道点数为n,边数为m.可以标记若干个点,如果一个点被标记,那么与它距离不超过k的点(包括本身)都会被覆盖. 显然对于每张不同图,让所有点被覆盖的最小代价是不一 ...

  9. Eclipse中构建scala开发环境的步骤

    Eclipse是一款非常使用的开发工具,熟悉它的童鞋应该都知道,它不仅是最常用的android开发工具,还是最常用的Java开发工具.既然eclipse如此重要,本文小编就和大家一起来扒一扒在ecli ...

  10. 计蒜客16495 Truefriend(fwt)

    #include <iostream> #include <cstring> #include <cstdio> using namespace std; type ...