Skip to content

Redis with redis-py (Python)

Uses redis-py 8.1. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.

redis://:secret@redis.example.com:6379/0
redis://:secret@machnosql.example.com:6379/0

The address comes from the environment variable REDIS_URL, so switching to MachNoSQL changes configuration only.

Terminal window
export REDIS_URL='redis://:secret@machnosql.example.com:6379/0'
pip install -r requirements.txt
python app.py

The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.

app.py
"""Cache, counter, session and leaderboard on Redis, unchanged on MachNoSQL."""
import os
import redis
r = redis.Redis.from_url(os.environ["REDIS_URL"], decode_responses=True)
r.set("cache:home", "<html>...</html>", ex=60)
print("cached:", r.get("cache:home"), "ttl:", r.ttl("cache:home"))
print("views:", r.incr("views:home"))
r.hset("session:42", mapping={"user": "ada", "cart_items": 3})
print("session:", r.hgetall("session:42"))
r.zadd("leaderboard", {"ada": 120, "linus": 95, "grace": 130})
print("top:", r.zrevrange("leaderboard", 0, 2, withscores=True))
with r.pipeline(transaction=True) as pipe:
pipe.incr("orders:count").lpush("orders:recent", "order-1001").ltrim("orders:recent", 0, 99)
print("pipeline:", pipe.execute())
requirements.txt
redis==8.1.0