Last active
December 23, 2021 09:12
-
-
Save amatmv/788e6ca71325b7f9fc2c7d2271f7f2c6 to your computer and use it in GitHub Desktop.
Get values from redis sessions in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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