简体   繁体   English

在GraphQL突变中设置cookie

[英]Set cookie in GraphQL mutation

I need to update a cookie in GraphQL mutation using graphene and Django. 我需要使用石墨烯和Django更新GraphQL突变形式的cookie。

My first idea was to add cookie to context (which is request) and then set it in middleware. 我的第一个想法是将cookie添加到上下文(这是请求),然后在中间件中进行设置。

I have a very simple mutation that looks like that: 我有一个非常简单的变异,看起来像这样:

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)

And Django Middleware is that: 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

But I cannot get wanted_cookie in my CookieMiddleware . 但是我无法在wanted_cookie中获得wanted_cookie CookieMiddleware

Any ideas how to set cookie in mutation/moddlewere? 有任何想法如何设置cookie的突变/模块吗? Or what are other ways to set cookie through graphene mutation? 或通过石墨烯突变设置cookie的其他方法有哪些?

One way to do this is to check the operation name in the json of the request: 一种方法是在请求的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

Note that it looks like you're using a version of Django pre-1.10 and should consider upgrading . 请注意,您似乎正在使用Django 1.10之前的版本, 应该考虑进行升级

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM