clo*_*dal 6 python graphql graphene-python
在Graphene Python 中,schema.py当无法访问HttpResponse要设置 cookie的对象时,应该如何设置 cookie?
我当前的实现是通过捕获data.operationName. 这涉及我需要设置 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
Run Code Online (Sandbox Code Playgroud)
有没有更简洁的方法来为特定的 Graphene Python 突变设置 cookie?
最后通过中间件设置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
...
Run Code Online (Sandbox Code Playgroud)
在自定义 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
Run Code Online (Sandbox Code Playgroud)