石墨烯模式中的 Django http 请求

Esp*_*and 5 django schema request django-sessions graphene-python

如何将 http-request-session 对象获取到石墨烯模式中?

我已在请求会话中存储了一些值,我需要通过这些值进行访问。一种可能的解决方案是将 session-id 发送到前端,然后将其传递到 post 请求中,但这似乎不是一个好的解决方案。

石墨烯有一个 context_value 但我不明白我是如何工作的。

我将其放入我的 Django 视图中:

schema = graphene.Schema()
schema.execute('{ viewer }', context_value={'session': request.session})
Run Code Online (Sandbox Code Playgroud)

在我的石墨烯模式中,如果我尝试按照教程中描述的方式进行操作(https://github.com/graphql-python/graphene/blob/master/docs/execution/execute.rst),它会说

“WSGIRequest”对象没有属性“get”

class Query(graphene.ObjectType):
  viewer = graphene.Field(Viewer)

  def resolve_viewer(self, info):
    info.context.get('session')
    print(info.context.session.keys()) #an empty array
    return Viewer()
Run Code Online (Sandbox Code Playgroud)

Mar*_*ian 5

您可以在解析方法中访问Django 会话info.context.session

例如

print("session:", info.context.session)
print("keys:", info.context.session.keys())
Run Code Online (Sandbox Code Playgroud)

在解析器中为我输出

session: <django.contrib.sessions.backends.db.SessionStore object at 0x7fa98e6ddac8>
keys: dict_keys(['_auth_user_id', '_auth_user_backend', '_auth_user_hash'])
Run Code Online (Sandbox Code Playgroud)

您可以检查以进行调试的一些内容:

  1. 确保会话中间件已配置

  2. 如果你schema在 Django 中构建一个对象,你想要的格式是result = schema.execute(query, context_value=request)-- 有关更多详细信息,请参阅我在 Django 中的 GraphQL 查询返回 None 中的回答