Skip to content

Instantly share code, notes, and snippets.

@amatmv
Last active December 23, 2021 09:12
Show Gist options
  • Save amatmv/788e6ca71325b7f9fc2c7d2271f7f2c6 to your computer and use it in GitHub Desktop.
Save amatmv/788e6ca71325b7f9fc2c7d2271f7f2c6 to your computer and use it in GitHub Desktop.
Get values from redis sessions in Django
from django.conf import settings
from importlib import import_module
from redis import Redis
import base64
import json
SESSION_KEY = 'examplehashsessionid'
def get_value_from_redis(key=SESSION_KEY):
""" Get value from the DB using redis cli """
conn = Redis(
host=settings.SESSION_REDIS['host'],
db=settings.SESSION_REDIS['db'],
port=settings.SESSION_REDIS['port'],
password=settings.SESSION_REDIS['password'],
)
value_b64 = conn.get(session.get_real_stored_key(key))
session_value = base64.b64decode(value_b64)
skey, svalue = session_value.decode().split(':', 1)
return str(skey), json.loads(svalue)
def get_value_from_session_store(key=SESSION_KEY):
engine = import_module(settings.SESSION_ENGINE)
session = engine.SessionStore(session_key=key)
return session.load()
# Get value from redis directly
get_value_from_redis()
# Also we can use session store to get the value
get_value_from_session_store()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment