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.
The only change
Section titled “The only change”redis://:secret@redis.example.com:6379/0redis://:secret@machnosql.example.com:6379/0The address comes from the environment variable REDIS_URL, so switching to MachNoSQL changes configuration only.
export REDIS_URL='redis://:secret@machnosql.example.com:6379/0'pip install -r requirements.txtpython app.pySource
Section titled “Source”The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.
"""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())redis==8.1.0