Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NoCsrfForJSONGraphQLView.py
from graphene_django.views import GraphQLView
from django.conf import settings
from django.utils.decorators import classonlymethod
from django.views.decorators.csrf import csrf_protect, csrf_exempt
class NoCsrfForJSONGraphQLView(GraphQLView):
@classonlymethod
def as_view(cls, **kwargs):
view = super(NoCsrfForJSONGraphQLView, cls).as_view(**kwargs)
view = csrf_exempt(view)
return view
def dispatch(self, request, *args, **kwargs):
super_dispatch = super(NoCsrfForJSONGraphQLView, self).dispatch
if request.content_type != 'application/json':
super_dispatch = csrf_protect(super_dispatch)
response = super_dispatch(request, *args, **kwargs)
if getattr(response, 'csrf_cookie_set', False) and response['Content-Type'] == 'application/json':
response.cookies.pop(settings.CSRF_COOKIE_NAME)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment