在Django中对于基于函数的视图我们可以 @csrf_exempt 注解来标识一个视图可以被跨域访问。那么对于基于类的
在Django中对于基于函数的视图我们可以 @csrf_exempt 注解来标识一个视图可以被跨域访问。那么对于基于类的视图,我们应该怎么办呢?
两种访问来解决
方法一:在类的 dispatch 方法上使用 @csrf_exempt
from django.views.decorators.csrf import csrf_exempt
class MyView(View):
def get(self, request):
return HttpResponse("hi")
def post(self, request):
return HttpResponse("hi")
@csrf_exempt
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
官方用的另一种方法,例子如下:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
class ProtectedView(TemplateView):
template_name = 'secret.html'
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
# 更简洁地说,您可以改为装饰类,并将要装饰的方法的名称作为关键字参数传递name。
# 如果有多个模型,则可以定义装饰器的列表或元组,而不是多次调用method_decorator(),这两个类是等价的::
decorators = [never_cache, login_required]
@method_decorator(decorators, name='dispatch')
class ProtectedView(TemplateView):
template_name = 'secret.html'
@method_decorator(never_cache, name='dispatch')
@method_decorator(login_required, name='dispatch')
class ProtectedView(TemplateView):
template_name = 'secret.html'
方法二:在 urls.py 中配置
from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
import views
urlpatterns = [
url(r'^myview/$', csrf_exempt(views.MyView.as_view()), name='myview'),
]
官方引用链接如下: https://docs.djangoproject.com/zh-hans/2.1/topics/class-based-views/intro/
发表评论