django csrf 검사 면제 방법

2632 단어 djangocsrf 검사

csrf 검사 면제


django에서 기본적으로 csrf 검사를 시작합니다. 사용자가post 요청을 할 때 csrf_를 휴대해야 합니다.token 매개 변수.csrf 검사를 사용하지 않으려면 다음과 같은 방식으로 검사를 면제할 수 있습니다.다음 방식은 모두 국부적으로 사용됩니다. 전역적으로 사용하지 않으려면settings 파일에서 설정해야 합니다. 이런 방식은 추천하지 않습니다.

1. 함수 csrf 검사 면제


from django.views.decorators.csrf import csrf_exempt#  csrf @csrf_exempt
def users(request):    
 uses_list = [" ", " "]    
 return HttpResponse(json.dumps(uses_list))

2. 클래스에 대한 csrf 검사 면제


첫 번째 방식


# dispatch , dispatch 

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
class StudentsView(View):
    """student view"""
 @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        print("before")
        ret = super(StudentsView, self).dispatch(request, *args, **kwargs)
        print("after")
        return ret(request, *args, **kwargs)
    
    def get(self,*args,**kwargs):
        return HttpResponse("get")

    def post(self,*args,**kwargs):
        return HttpResponse("post")

    def put(self,*args,**kwargs):
        return HttpResponse("put")

    def delete(self,*args,**kwargs):
        return HttpResponse("delete")

두 번째 방식


from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt,name="dispatch")
class StudentsView(View):
    """student view"""

    def get(self,*args,**kwargs):
        return HttpResponse("get")


세 번째 방식


from django.views.decorators.csrf import csrf_exempt
class MyBaseView(object):
    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        print("before")
        ret = super(MyBaseView, self).dispatch(request, *args, **kwargs)
        print("after")
        return ret

네 번째, URL에 추가


from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
    path('teachers/', csrf_exempt(TeachersView.as_view()), name="teachers"),
]
django csrf 검사 면제 방법에 관한 이 글은 여기까지 소개합니다. 더 많은 관련 django 검사 면제 내용은 저희 이전의 글을 검색하거나 아래의 관련 글을 계속 훑어보십시오. 앞으로 많은 응원 부탁드립니다!

좋은 웹페이지 즐겨찾기