Search code examples
djangorequestschemadjango-sessionsgraphene-python

Django http-request in graphene schema


How do I get the http-request-session object into a graphene schema?

I have stored som values in request session that I need access thru. A possible solution is to send the session-id to the frontend and then pass it into the post request, but that does not seem like a good solution.

Graphene hast a context_value but I don't understand how I works.

Into my Django-views I put this:

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

In my graphene schema if I try to do like described in the tutorial(https://github.com/graphql-python/graphene/blob/master/docs/execution/execute.rst), it says

'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()

Solution

  • You can access a Django session in a resolve method with info.context.session

    For example

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

    in a resolver outputs for me

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

    Some things that you can check to debug:

    1. make sure the session middleware is configured

    2. if you're constructing a schema object in Django, the format you want is result = schema.execute(query, context_value=request) -- for more details see my answer at GraphQL queries in Django returning None