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. tomcat 异常

    Removing obsolete files from server... Could not clean server of obsolete files: null java.lang.Null ...

  2. 《python核心编程第二版》第4章习题

    4–1. Python 对象.与所有 Python 对象有关的三个属性是什么?请简单的

  3. Jmeter从文件中读取参数值

    1. 通过函数助手,从本地文件中取值选项->函数助手对话框->选择__CSVRead函数->调用参数其中,函数助手对话框中,第一栏填写本地文件所在地址,第二栏写需要入参的值,有点类似 ...

  4. 定时爬虫抓当日免费应用:Scrapy + Tkinter + LaunchControl

    花了个周末学了下Scrapy,正好一直想买mindnode,于是顺手做了个爬虫,抓取爱范儿每天的限免应用信息. Thinking 大概思路就是使用LaunchControl每天定时(比如早上9点50, ...

  5. LINQ学习笔记——(3)基本查询操作符

    Select() 作用于uIEnumerable<TSource>类型 public static void Test() { List<string> persons = n ...

  6. Leetcode 55. Jump Game & 45. Jump Game II

    55. Jump Game Description Given an array of non-negative integers, you are initially positioned at t ...

  7. Cassandra 常见错误索引

    类型错误 类型错误调试的技巧 有时候,类型错误提示比较不友好,比如不知道哪个字段出错. 在php中可以用 //过滤几个数据进行操作,逐个检查,或者折半查找错误 $data = array_splice ...

  8. Daily Scrum02 12.02

    今天是黑色星期一,虽然大家最近被各种大作业压得身心疲惫,但是团队的凝聚力战胜了一切不快. 看看同志们今天的战绩,是不是又有一种充实感油然而生呢??? By Ryan Mao who? Today? T ...

  9. winspool.drv

    public partial class Form1 : Form{ [System.Runtime.InteropServices.DllImportAttribute("winspool ...

  10. Flink History Job

    history job的写入1. org.apache.flink.runtime.jobmanager,Object JobManagerrunJobManager中指定使用MemoryArchiv ...