0

I was read contrib/sessions/backend/db.py file and i see

        session_key=self._get_or_create_session_key(),
        session_data=self.encode(self._get_session(no_load=must_create)),
        expire_date=self.get_expiry_date()

That mean Django store session_key, session_data and expire_date. If i have a line

        request.session['user_id'] = "my_user_id"

I use Redis and Engine for my test. My question is How it can be stored to Redis?

Thank for advance!

2 Answers2

0

Django sessions are basically dictionary-like objects which can be serialized and de-serialized to the session backend (see encode, decode).

https://github.com/django/django/blob/master/django/contrib/sessions/backends/base.py#L87

The session encoder uses Python pickle (Django -1.5) and JSON (Django 1.6+) and it can be configured:

https://docs.djangoproject.com/en/dev/ref/settings/#session-serializer

You can change the session backend in Django settings:

https://docs.djangoproject.com/en/dev/ref/settings/#session-engine

One of the default session backends is the database engine.

If you want to use different Django settings for your unit tests, there are many ways to override specific settings:

How to Unit test with different settings in Django?

Community
  • 1
  • 1
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
0

Not sure what is that you are asking, I assume that you want to know how session is store in redis. If that is the case, then reading the source code from https://gist.github.com/mikeyk/910392 provides all the answer

encoded_data = self.encode(self._session)
self.redis.setex(self._redis_key(), encoded_data, settings.SESSION_COOKIE_AGE)

The session data is first encoded and then save to redis using SETEX command. Then when you want to retrieve it

session_data = self.redis.get(self._redis_key())
if session_data is not None:
    return self.decode(force_unicode(session_data))

The data is GET from redis which is now a normal string, and then is decoded into regular Python dict

If you want to see the actual data, use redis-cli and do keys * then get [key]

Tan Nguyen
  • 3,354
  • 3
  • 21
  • 18