2017-08-17 59 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