django-cbv模式-csrf中间件
1. django模式
def users(request):
user_list = ['alex','oldboy']
return HttpResponse(json.dumps((user_list)))
FBV,function base view
路由:
url(r'^students/', views.StudentsView.as_view()),
视图: 通过发射来找到对应的方法去执行
from django.views import View
class StudentsView(View):
def get(self,request,*args,**kwargs):
return HttpResponse('GET') def post(self, request, *args, **kwargs):
return HttpResponse('POST') def put(self, request, *args, **kwargs):
return HttpResponse('PUT') def delete(self, request, *args, **kwargs):
return HttpResponse('DELETE')
CBV,class base view
详谈cbv工作模式
基于反射实现根据请求的方式不同,执行不同的方法
原理
-- url -> view方法 -> dispatch方法(反射执行其他:GET/POST/DELETE/PUT)
流程
class StudentsView(View):
def dispatch(self, request, *args, **kwargs):
print('before')
ret=super(StudentsView,self).dispatch(request,*args,**kwargs)
print('after')
return ret def get(self,request,*args,**kwargs):
return HttpResponse('GET') def post(self, request, *args, **kwargs):
return HttpResponse('POST') def put(self, request, *args, **kwargs):
return HttpResponse('PUT') def delete(self, request, *args, **kwargs):
return HttpResponse('DELETE')
cbv执行父类的dispatch方法
2. 面向对象的继承
多个类共用的功能,为了避免重复编写
from django.views import View
最左原则
class MyBaseView(object):
def dispatch(self, request, *args, **kwargs):
print('before')
ret = super(MyBaseView, self).dispatch(request, *args, **kwargs)
print('after')
return ret class StudentsView(MyBaseView, View):
def get(self, request, *args, **kwargs):
print('get方法')
return HttpResponse('GET') def post(self, request, *args, **kwargs):
return HttpResponse('POST') def put(self, request, *args, **kwargs):
return HttpResponse('PUT') def delete(self, request, *args, **kwargs):
return HttpResponse('DELETE') class TeachersView(MyBaseView, View):
def get(self, request, *args, **kwargs):
return HttpResponse('GET') def post(self, request, *args, **kwargs):
return HttpResponse('POST') def put(self, request, *args, **kwargs):
return HttpResponse('PUT') def delete(self, request, *args, **kwargs):
return HttpResponse('DELETE')
继承父类的dispatch方法
3. 面向对象的封装
class File:
文件增删改查方法 Class DB:
数据库的方法
同一类方法封装到类中
class File:
def __init__(self,a1,a2):
self.a1 = a1
self.xxx = a2
def get:...
def delete:...
def update:...
def add:... obj1 = File(123,666) 将数据123,666 封装到对象中
obj2 = File(456,999)
数据封装到对象中
from django.test import TestCase # Create your tests here. ## 封装示例 class Request(object):
def __init__(self,obj): # OBJ=对象B,AUTH的这个对象
self.obj = obj @property # 静态方法
def user(self): # REQ.USER执行这里,返回 self.obj.authticate() = self.B.authticat() = Auth.authticat() = 'JOKER'
return self.obj.authticate() class Auth(object):
def __init__(self,name,age): # NAME=JOKER,AGE=18
self.name = name
self.age = age def authticate(self):
return self.name # 返回类的属性NAME class APIView(object):
def dispatch(self): # 方法被执行
self.f2() # SELF就是这个类,调用F2() def f2(self): # 调用属性方法
b = Auth('joker',18) # 实例化Auth,得到对象B
req = Request(b) # 实例化Request,得到对象REQ
print(req.user) # obj = APIView() # 得到APIView实例化对象OBJ
obj.dispatch() # 调用属性方法
封装示例
4. django中间件
- process_request
- process_view
- process_response
- process_exception
- process_render_template
五种方法
中间件做过什么?
-权限 -登陆验证
4.1 django的csrf是如何实现?
发生在,process_view方法,因为要检查函数是否被装饰器装饰
- 检查视图是否被 @csrf_exempt (免除csrf认证)
- 去请求体或cookie中获取token
请求时候会随机产生字符串,在访问的时候会携带这个随机字符串
4.2 针对django,fbv模式如何关闭验证
from django.views.decorators.csrf import csrf_exempt(无需验证),csrf_protect(需验证)
找到需要验证的函数,@csrf_exempt,@csrf_protect
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware', # 全站使用csrf认证
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
] from django.views.decorators.csrf import csrf_exempt @csrf_exempt # 该函数无需认证
def users(request):
user_list = ['alex', 'oldboy']
return HttpResponse(json.dumps((user_list)))
情况一,全局验证,该函数无需验证
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware', # 全站不使用csrf认证
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
] from django.views.decorators.csrf import csrf_protect @csrf_protect # 该函数需认证
def users(request):
user_list = ['alex', 'oldboy']
return HttpResponse(json.dumps((user_list)))
情况二,全局不验证,该函数需验证
4.3 针对django, cbv模式如何关闭验证
dispatch函数,或者方法,是通过反射来执行相对应的方法,控制它的验证或不验证
from django.views.decorators.csrf import csrf_exempt(无需验证),csrf_protect(需验证)
from django.utils.decorators import method_decorator
- @method_decorator(csrf_exempt)
- 在dispatch方法中(单独方法无效)
可以针对验证的函数去写,但是不能单独写,要写在@method_decorator里面
@method_decorator(csrf_exempt),@method_decorator(csrf_protect)
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.utils.decorators import method_decorator class StudentsView(View):
@method_decorator(csrf_exempt) # 无需验证
def dispatch(self, request, *args, **kwargs):
return super(StudentsView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs):
print('get方法')
return HttpResponse('GET') def post(self, request, *args, **kwargs):
return HttpResponse('POST') def put(self, request, *args, **kwargs):
return HttpResponse('PUT') def delete(self, request, *args, **kwargs):
return HttpResponse('DELETE')
针对dispatch函数
可以针对类,然后指定类里面的方法去验证还是不验证,同样需要写在@method_decorator里面
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.utils.decorators import method_decorator @method_decorator(csrf_exempt, name='dispatch') # 无需验证
class StudentsView(View): def get(self, request, *args, **kwargs):
print('get方法')
return HttpResponse('GET') def post(self, request, *args, **kwargs):
return HttpResponse('POST') def put(self, request, *args, **kwargs):
return HttpResponse('PUT') def delete(self, request, *args, **kwargs):
return HttpResponse('DELETE')
针对dispatch方法
5. 总结
- cbv
- 本质,基于反射来实现
- 流程:路由,view,dispatch(反射)
- 取消csrf认证(装饰器要加到dispatch方法上且method_decorator装饰)
- csrf
- 基于中间件的process_view方法
- 装饰器给单独函数进行设置(认证或无需认证)
-urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^students/', views.StudentsView.as_view()), 点 as_view查看源码
]
class View(object):
"""
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
""" http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] def __init__(self, **kwargs):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in six.iteritems(kwargs):
setattr(self, key, value) @classonlymethod
def as_view(cls, **initkwargs):
"""
Main entry point for a request-response process.
"""
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key)) def view(request, *args, **kwargs):
self = cls(**initkwargs)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs)
view.view_class = cls
view.view_initkwargs = initkwargs # take name and docstring from class
update_wrapper(view, cls, updated=()) # and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
cbv反射源码
django请求周期
FBV wsgi--中间件--路由--视图--模版--渲染--返回
CBV wsgi--中间件--路由--dispatch
RESTFRAMEWORK wsgi--中间件--路由--dispatch
django-cbv模式-csrf中间件的更多相关文章
- Django CBV装饰器 中间件 auth模块 CSRF跨站请求
CBV添加装饰器 给CBV添加装饰器有三种方法,三种方法都需要导入模块: from django.utils.decorators import method_decorator 第一种直接在方法上面 ...
- django CBV模式下如何去掉csrf验证
方式一:from django.views.decorators.csrf import csrf_exemptfrom django.utils.decorators import method_d ...
- django CBV模式源码执行过程
在说CBV模式之前,先看下FBV的url配置方式: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^xxx/', login), ur ...
- django:CBV模式,源码解析
非常好 DRF执行流程源码解析 https://www.cnblogs.com/suguangti/p/11120793.html https://www.cnblogs.com/haitaoli/p ...
- Django之csrf中间件及auth模块使用
目录 一.基于配置文件的编程思想 1. importlib 模块 2. 配置文件 二.跨站请求伪造(csrf) 1.csrf简介以及由来 2.Django中的csrf中间件如何使用 2.1 普通for ...
- 源码解析Django CBV的本质
Django CBV模式的源码解析 通常来说,http请求的本质就是基于Socket Django的视图函数,可以基于FBV模式,也可以基于CBV模式. 基于FBV的模式就是在Django的路由映射表 ...
- django框架进阶-CSRF认证
############################################### """ django中csrf的实现机制 #第一步:django第一次响应 ...
- django CBV装饰器 自定义django中间件 csrf跨站请求伪造 auth认证模块
CBV加装饰器 第一种 @method_decorator(装饰器) 加在get上 第二种 @method_decorator(login_auth,name='get') 加在类上 第三种 @met ...
- Django中请求的生命周期 和 FBV模式和CBV模式
Django的生命周期就是你的 一个请求所发生的整个流程 Django的生命周期内到底发生了什么呢?? . 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端 请求头和请求体中会包含浏 ...
随机推荐
- 疑问:@Autowired的作用?[待解答]
有下面一个Spring的工程,工程结构如下: 代码如下: applicationContext.xml: <?xml version="1.0" encoding=" ...
- Linux:grep命令详解
grep grep(global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具, ...
- 迭代器、foreach循环、泛型集合
集合的迭代 语法:Iterator<Object> it=集合.iterator(); while(it.hasNext()){ Object obj=it.next(); } is.ha ...
- HM visual studio编译报错
今天,编译HM的代码,发现编译报如下错误. error MSB6003: The specified task executable "cl.exe" could not be r ...
- String,StringBuffer和StringBuilder比较
String:查看源码得知,String类的声明是:public final,所以可以很清楚的知道,fianl的话是改变不了的,所以,如果我们用String来操作字符串的时候,一旦我们字符串的值改变, ...
- Android程序员学WEB前端(4)-HTML(4)-注册页面-Sublime
转载请注明出处:http://blog.csdn.net/iwanghang/article/details/76576031 觉得博文有用,请点赞,请评论,请关注,谢谢!~ 注册页面1: <! ...
- CUDA Samples: ripple
以下CUDA sample是分别用C++和CUDA实现的生成的波纹图像,并对其中使用到的CUDA函数进行了解说,code参考了<GPU高性能编程CUDA实战>一书的第五章,各个文件内容如下 ...
- loadrunner11 中文破解版安装教程
loadrunner11的安装:http://pan.baidu.com/share/link?shareid=316642707&uk=1395568298 汉化包(下载之后有可能是ISO格 ...
- 利用sklearn的LabelEncoder对标签进行数字化编码
from sklearn.preprocessing import LabelEncoder def gen_label_encoder(): labels = ['BB', 'CC'] le = L ...
- iOS下简单实现滑动导航条
功能介绍 最近在做一款ios的app,其中有一个页面需要分成三个版块,版块之间可以通过左右滑动来进行切换,也可以通过点击上方的按钮来切换,好像在android中可以用过ViewPager + Frag ...