Skip to content

Instantly share code, notes, and snippets.

@dex4er
Last active April 17, 2019 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dex4er/aa5a4bfc169ba92d56f70111471a535e to your computer and use it in GitHub Desktop.
Save dex4er/aa5a4bfc169ba92d56f70111471a535e to your computer and use it in GitHub Desktop.
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