Source code for django.views.decorators.csrf

fromfunctoolsimportwrapsfromdjango.middleware.csrfimportCsrfViewMiddleware,get_tokenfromdjango.utils.decoratorsimportdecorator_from_middlewarecsrf_protect=decorator_from_middleware(CsrfViewMiddleware)csrf_protect.__name__="csrf_protect"csrf_protect.__doc__="""This decorator adds CSRF protection in exactly the same way asCsrfViewMiddleware, but it can be used on a per view basis. Using both, orusing the decorator multiple times, is harmless and efficient."""class_EnsureCsrfToken(CsrfViewMiddleware):# Behave like CsrfViewMiddleware but don't reject requests or log warnings.def_reject(self,request,reason):returnNonerequires_csrf_token=decorator_from_middleware(_EnsureCsrfToken)requires_csrf_token.__name__='requires_csrf_token'requires_csrf_token.__doc__="""Use this decorator on views that need a correct csrf_token available toRequestContext, but without the CSRF protection that csrf_protectenforces."""class_EnsureCsrfCookie(CsrfViewMiddleware):def_reject(self,request,reason):returnNonedefprocess_view(self,request,callback,callback_args,callback_kwargs):retval=super().process_view(request,callback,callback_args,callback_kwargs)# Force process_response to send the cookieget_token(request)returnretvalensure_csrf_cookie=decorator_from_middleware(_EnsureCsrfCookie)ensure_csrf_cookie.__name__='ensure_csrf_cookie'ensure_csrf_cookie.__doc__="""Use this decorator to ensure that a view sets a CSRF cookie, whether or not ituses the csrf_token template tag, or the CsrfViewMiddleware is used."""

[docs]defcsrf_exempt(view_func):"""Mark a view function as being exempt from the CSRF view protection."""# view_func.csrf_exempt = True would also work, but decorators are nicer# if they don't have side effects, so return a new function.defwrapped_view(*args,**kwargs):returnview_func(*args,**kwargs)wrapped_view.csrf_exempt=Truereturnwraps(view_func)(wrapped_view)