在GraphQL突变中设置cookie

时间:2019-06-24 16:38:19

标签: python django graphql graphene-python graphene-django

我需要使用石墨烯和Django更新GraphQL突变形式的cookie。

我的第一个想法是将cookie添加到上下文(这是请求),然后在中间件中进行设置。

我有一个非常简单的突变,看起来像这样:

class SetWantedCookieMutation(graphene.Mutation):

    class Arguments:
        wanted_cookie = graphene.String(required=True)

    ok = graphene.Boolean(required=True)

    def mutate(self, info, wanted_cookie):
        # set cookie here 
        info.context.wanted_cookie = wanted_cookie

        return SetWantedCookieMutation(ok=True)

而Django中间件是:

class CookieMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        if (hasattr(request, 'wanted_cookie')):
            response.set_cookie('wanted_cookie', request.wanted_cookie)
        return response

但是我无法在wanted_cookie中获得CookieMiddleware

有人提出过如何在cookie中设置cookie的信息吗? 或通过石墨烯突变设置cookie的其他方法有哪些?

1 个答案:

答案 0 :(得分:0)

一种方法是检查请求的json中的操作名称:


class CookieMiddleware(MiddlewareMixin):

    def generate_cookie(self, user):
        # Generate a cookie (probably with the user)

    def request_has_cookie_mutation(self, request):
        # Returns true if the request's operation is SetWantedCookieMutation
        if len(request.body) != 0 and 'operationName' in json.loads(request.body):
            return json.loads(request.body)['operationName'] == 'SetWantedCookieMutation'
        return False

    def process_response(self, request, response):
        if (self.request_has_cookie_mutation(request)):
            new_cookie = self.generate_cookie(request.user)
            response.set_cookie('wanted_cookie', new_cookie)
        return response

请注意,您似乎正在使用Django 1.10之前版本和should consider upgrading