【问题标题】:Set cookie in GraphQL mutation在 GraphQL 突变中设置 cookie
【发布时间】:2019-11-06 12:10:58
【问题描述】:

我需要使用石墨烯和 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

但我无法在我的CookieMiddleware 中获得wanted_cookie

任何想法如何在突变/moddlewere 中设置 cookie? 或者通过石墨烯突变设置cookie的其他方法是什么?

【问题讨论】:

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


    【解决方案1】:

    一种方法是检查请求的 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

    【讨论】:

      猜你喜欢
      • 2019-11-27
      • 2018-01-25
      • 2020-11-21
      • 2017-10-09
      • 1970-01-01
      • 2020-07-26
      • 2019-01-23
      • 2021-03-09
      • 2019-08-21
      相关资源
      最近更新 更多