简体   繁体   English

如何在 Graphene Python 突变中设置 cookie?

[英]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?Graphene Python 中,当无法访问HttpResponse对象来设置 cookie 时,应该如何在schema.py中设置 cookie?

My current implementation is to set the cookie by overriding the GraphQLView's dispatch method by catching the data.operationName .我当前的实现是通过捕获data.operationName来覆盖 GraphQLView 的 dispatch 方法来设置 cookie。 This involves hard-coding of the operation names / mutations that I need cookies to be set on.这涉及我需要设置 cookie 的操作名称/突变的硬编码。

In views.py:在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?有没有更简洁的方法来为特定的 Graphene Python 突变设置 cookie?

Wound up setting cookies via middleware.结束了通过中间件设置 cookie。

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.在自定义 graphql 视图中, views.py覆盖 dispatch 方法以读取 cookie 并设置它。

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

I had a similar problem.我有一个类似的问题。 I needed to be able to set the language cookie in a mutation and ended up using the request instance in combination with a custom middleware.我需要能够在突变中设置语言 cookie,并最终将请求实例与自定义中间件结合使用。

Here's the simplified code:这是简化的代码:

class SetLanguage(Mutation):
    class Arguments:
        code = String(required=True)

    ok = Field(Boolean)
    language = Field(LanguageType)

    def mutate(root, info, code):
        info.context.set_language_cookie = code
        return SetLanguage(ok=True, language=code)

The mutation doesn't have access to the response so it temporarily stores the value on the request instance.突变无法访问响应,因此它会临时将值存储在请求实例上。 Once the response has been created a custom middleware retrieves it and sets the cookie:创建响应后,自定义中间件会检索它并设置 cookie:

class LanguageConfigMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        if code := getattr(request, "set_language_cookie", None):
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, code)

        return response

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

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