Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cookies in Graphene Python mutation?

In Graphene Python, how should one go about setting cookies in the schema.py when there is no access to the HttpResponse object to set the cookie on?

My current implementation is to set the cookie by overriding the GraphQLView's dispatch method by catching the data.operationName. This involves hard-coding of the operation names / mutations that I need cookies to be set on.

In views.py:

class PrivateGraphQLView(GraphQLView):
    data = self.parse_body(request)
    operation_name = data.get('operationName')
    # hard-coding === not pretty.
    if operation_name in ['loginUser', 'createUser']:
        ...
        response.set_cookie(...)
    return response

Is there a cleaner way of setting cookies for specific Graphene Python mutations?

like image 674
clodal Avatar asked Aug 17 '17 09:08

clodal


1 Answers

Wound up setting cookies via middleware.

class CookieMiddleware(object):

    def resolve(self, next, root, args, context, info):
        """
        Set cookies based on the name/type of the GraphQL operation
        """

        # set cookie here and pass to dispatch method later to set in response
        ...

In a custom graphql view, views.py, override the dispatch method to read the cookie and set it.

class MyCustomGraphQLView(GraphQLView):  

    def dispatch(self, request, *args, **kwargs):
        response = super(MyCustomGraphQLView, self).dispatch(request, *args, **kwargs)
        # Set response cookies defined in middleware
        if response.status_code == 200:
            try:
                response_cookies = getattr(request, CookieMiddleware.MIDDLEWARE_COOKIES)
            except:
                pass
            else:
                for cookie in response_cookies:
                    response.set_cookie(cookie.get('key'), cookie.get('value'), **cookie.get('kwargs'))
        return response
like image 166
clodal Avatar answered Oct 01 '22 17:10

clodal