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.路由系统 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")
相关推荐
为了在类方法上使用装饰器,我们需要引入`method_decorator`。 1. **导入装饰器模块**: ```python from django.utils.decorators import method_decorator ``` 2. **定义装饰器**: ```python def outer(func): ...
Django通过method_decorator来支持将函数装饰器转换为方法装饰器,实现为类中的方法添加额外功能的目的。 **数据库迁移** Django默认使用SQLite数据库,但在生产环境中,我们通常会切换到更强大的数据库系统,如...
用法只需导入装饰器,使用并返回JSON可序列化的对象即可: from jsonview.decorators import json_view@json_viewdef my_view(request): return { 'foo': 'bar', }(CBV)可以从JsonView继承,使用Django的@method_...
CBV还可以利用装饰器和方法修饰器来增强功能,例如: ```python from django.utils.decorators import method_decorator def outer(func): def inner(request, *args, **kwargs): return func(request, *args, **...
对于Class-Based Views(CBV),你可以使用`@method_decorator`配合`csrf_exempt`或`csrf_protect`装饰器。例如: ```python from django.views.decorators.csrf import csrf_exempt, csrf_protect from django....
- **实现方式**:对于不需要CSRF保护的视图,可以使用`csrf_exempt`装饰器。 - **函数视图**(FBV): ```python from django.views.decorators.csrf import csrf_exempt @csrf_exempt def add_data(request)...
该装饰器可用于函数视图(FBV)和类视图(CBV)。 - **函数视图示例**: ```python from django.views.decorators.csrf import csrf_exempt @csrf_exempt def add_data(request): # 处理请求 return ...