石墨烯模式中的 Django http 请求

Django http-request in graphene schema

如何将 http-request-session 对象放入石墨烯架构中?

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

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

在我的 Django 视图中,我把这个:

schema = graphene.Schema()
schema.execute('{ viewer }', context_value={'session': request.session})

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

'WSGIRequest' object has no attribute '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()

您可以使用 info.context.session

在解析方法中访问 Django session

例如

print("session:", info.context.session)
print("keys:", info.context.session.keys())

在我的解析器输出中

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

一些你可以检查调试的东西:

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

  2. 如果你在 Django 中构造一个 schema 对象,你想要的格式是 result = schema.execute(query, context_value=request)——更多细节见我在 [ 的回答=17=]