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. mybatis <collection>标签 类型为string时无法获取重复数据错误

    1.场景: fyq_share_house 表 和 fyq_sh_tag 表 两张表是一对多的关系, 一个楼盘对应多个标签,在实体类ShareHouse中使用 /** * 楼盘标签 */ privat ...

  2. 常用模块(数据序列化 json、pickle、shelve)

    本节内容 前言 json模块 pickle模块 shelve模块 总结 一.前言 1. 现实需求 每种编程语言都有各自的数据类型,其中面向对象的编程语言还允许开发者自定义数据类型(如:自定义类),Py ...

  3. linux常用命令补充详细

    1.ls命令 就是list的缩写,通过ls 命令不仅可以查看linux文件夹包含的文件,而且可以查看文件权限(包括目录.文件夹.文件权限)查看目录信息等等 常用参数搭配: ls -a 列出目录所有文 ...

  4. Sersync实时备份服务部署实践

  5. Android 之Buletooth

    一:概要: Android提供了Buletooth的API ,通过API 我们可以进行如下的一些操作: 1.扫描其他的蓝牙设备 2.查询能配对的蓝牙设备 3.建立RFCOMM 通道 4.连接其他的蓝牙 ...

  6. springmvc项目搭建五-postgresql+easyui的数据显示

    上一篇虽然完成了页面的显示,但是是假数据,本篇添加了postgresql的数据库,将登陆的校验和数据的显示都通过数据库来完成. 我是在本地搭建了一个postgre的数据库,就先新建两张表吧,一个用于用 ...

  7. HDU 2135 Rolling table

    http://acm.hdu.edu.cn/showproblem.php?pid=2135 Problem Description After the 32nd ACM/ICPC regional ...

  8. tomcat8 管理页面403 Access Denied的解决方法

      安装tomcat,配置好tomcat环境变量以后,访问manager app页面,出现403 Access Denied错误,解决的方法如下: 首先在conf/tomcat-users.xml文件 ...

  9. 一个python游戏源码

    #finalPyPong.py import pygame,sys class MyBallClass(pygame.sprite.Sprite): def __init__(self,image_f ...

  10. WebSocket简单介绍(WebSocket 实战)(3)

    这一节里我们用一个案例来演示怎么使用 WebSocket 构建一个实时的 Web 应用.这是一个简单的实时多人聊天系统,包括客户端和服务端的实现.客户端通过浏览器向聊天服务器发起请求,服务器端解析客户 ...