脚本宝典收集整理的这篇文章主要介绍了@csrf_exempt,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
在Django中对于基于函数的视图我们可以 @csrf_exempt 注解来标识一个视图可以被跨域访问。那么对于基于类的视图,我们应该怎么办呢?
简单来说可以有两种访问来解决
方法一:在类的 dispatch 方法上使用 @csrf_exemptfrom 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(MyView, self).dispatch(*args, **kwargs)
方法二:在 urls.py 中配置from django.conf.urls import urlfrom django.views.decorators.csrf import csrf_exemptimport views
urlpatterns = [ url(r'^myview/$', csrf_exempt(views.MyView.as_view()), name='myview'),]
在views.py中
from django.views.generic.base import Viewclass ueditor(View): @csrf_exempt def post(self, request): print(request.POST.get('abc', "")) return render(request, "ueditor.html")这样写是csrf_exempt是不会生效的
只有继承了django rest framework的apiview有才用:
from rest_framework.views import APIViewclass ueditor(APIView): @csrf_exempt def post(self, request): print(request.POST.get('abc', "")) return render(request, "ueditor.html")
以上是脚本宝典为你收集整理的@csrf_exempt全部内容,希望文章能够帮你解决@csrf_exempt所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。