2017-08-17 44 views
0

Graphene Python中,当无法访问HttpResponse对象以设置Cookie时,应该如何设置schema.py中的cookie?如何在Graphene Python中设置Cookie变异?

我目前的实现是通过捕获data.operationName覆盖GraphQLView的调度方法来设置cookie。这涉及我需要设置Cookie的操作名称/突变的硬编码。

在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 

是否有特定的石墨烯Python的突变设置cookie的更清洁的方式?

回答

0

通过中间件创建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 
     ... 

在自定义graphql视图,views.py,重写调度方法来读取该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