How to Mock a Redis Session Store Cookie SID in Python

Mock a Redis-backed session store with a cookie-based session ID (SID) in Python, including the create, read, and delete operations.

Medium Python 3.9+ Aug 9, 2026 Caching & Redis 14 views 0 copies

Requires third-party packages — install first
pip install redis

Python code

56 lines
Python 3.9+
import redis
import uuid
import time


class RedisSessionStore:
    def __init__(self, host="localhost", port=6379, db=0, prefix="session:"):
        self.client = redis.Redis(host=host, port=port, db=db)
        self.prefix = prefix

    def create_session(self, timeout_seconds=3600):
        session_id = uuid.uuid4().hex
        key = f"{self.prefix}{session_id}"
        self.client.set(key, str(time.time()), ex=timeout_seconds)
        return session_id

    def get_session_data(self, session_id):
        key = f"{self.prefix}{session_id}"
        value = self.client.get(key)
        return value.decode("utf-8") if value else None

    def delete_session(self, session_id):
        key = f"{self.prefix}{session_id}"
        return self.client.delete(key)


class CookieMock:
    def __init__(self, session_store):
        self.session_store = session_store
        self.cookies = {}

    def set_cookie(self, session_id):
        self.cookies["sid"] = session_id
        return f"sid={session_id}; HttpOnly; Path=/"

    def get_cookie(self):
        session_id = self.cookies.get("sid")
        if not session_id:
            return None
        return self.session_store.get_session_data(session_id)

    def clear_cookie(self):
        session_id = self.cookies.pop("sid", None)
        if session_id:
            self.session_store.delete_session(session_id)


if __name__ == "__main__":
    store = RedisSessionStore()
    cookie_mock = CookieMock(store)

    sid = store.create_session(timeout_seconds=120)
    print("Session created:", cookie_mock.set_cookie(sid))
    print("Retrieved from cookie:", cookie_mock.get_cookie())
    cookie_mock.clear_cookie()
    print("After clearing:", cookie_mock.get_cookie())

Output

stdout
Session created: sid=<uuid-hex>; HttpOnly; Path=/
Retrieved from cookie: <timestamp>
After clearing: None

How it works

The RedisSessionStore class wraps a Redis client and stores session data with an expiration time using SET with EX. The CookieMock class simulates a web session cookie by storing the session ID in a dictionary and retrieving the session data from Redis. create_session generates a unique session ID with uuid.uuid4().hex, giving a 32-character hex string. The get_cookie method looks up the session ID in the mock cookie jar and fetches the corresponding data from Redis. This pattern mirrors how real web frameworks manage session cookies and serverside storage.

Common mistakes

  • Forgetting to set `ex` expiration on Redis keys, leaving sessions that never expire.
  • Not decoding the Redis value returned as bytes, causing a comparison error or unexpected output.
  • Using the same session ID for multiple sessions without checking uniqueness.
  • Forgetting to delete the session from Redis when clearing the cookie, leaking server-side data.

Variations

  1. Use a `redis.StrictRedis` subclass and a `Redis` connection pool for production concurrency.
  2. Replace the mock cookie storage with `http.cookies.SimpleCookie` to mimic a browser `Cookie` header.

Real-world use cases

  • Testing web application session handling without a real browser or server.
  • Building a lightweight session manager for a Flask or FastAPI app backed by Redis.
  • Storing user authentication state in high-traffic services where a shared Redis cache is already in use.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Caching & Redis

Related tutorials and quizzes for this topic.