1.CSRF
a.基本应用
form表单中添加
{% csrf_token %}
b.全栈禁用
# 'django.middleware.csrf.CsrfViewMiddleware',
c. 局部禁用
'django.middleware.csrf.CsrfViewMiddleware',
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def csrf1(request):
if request.method == 'GET':
return render(request,'csrf1.html')
else:
return HttpResponse('ok')
d.局部使用
# 'django.middleware.csrf.CsrfViewMiddleware',
from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_protect
def csrf1(request):
if request.method == "GET":
return render(request,'csrf1.html')
else:
return HttpResponse('OK')
c.特殊CBV
form django.views import View
from django.utls.decorators import method_decorator
@method_decorator(csrf_protect,name='dispatch')
class Foo(View):
def get(self,request):
pass
def post(self,request):
pass
PS:CBV中添加装饰器
def wrapper(func):
def inner(*args,**kwargs):
return func(*args,**kwargs)
return inner
#1.指定方法上添加装饰器
class Foo(View):
@method_decorator(wrapper)
def get(self,request):
pass
def post(self,request):
pass
2.在类上添加
@method_decorator(wrapper,name='dispatch')
class Foo(View):
def get(self,request):
pass
def post(self,request):
pass
#CBV代码
# 1.路由系统View Code
urlpatterns = [
url(r'^login.html$', views.Login.as_view()),
]
# 2.views类
"""
get 查
post 创建
put 更新
delete 删除
"""
# 根据request.method的方式自动执行对应的函数。
# 我们可以重写dispatch函数来实现类似装饰器的效果,dispatch内部根据反射来实现函数执行。
from django.views import View
class Login(View):
def get(self,request):
return render(request, "login.html")
def post(self, request):
name = request.POST.get("user")
print(name)
return HttpResponse("from post ")
def dispatch(self, request, *args, **kwargs):
print("-----before------")
ret = super().dispatch(request,*args,**kwargs)
print("-----after------")
return ret
# # CBV应用装饰器
# django的bug,不能直接对类进行装饰,必须使用 method_decorator,把装饰器当作参数传进去。
from django.utils.decorators import method_decorator
@method_decorator(wrapper, name="post")