tinycodinglm / sys /sys-0004.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 19)
034ba67 verified
|
Raw History Blame
2.31 kB
deepseek-harness trace
System You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing c...

You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies.

User

How do I use Redis for caching?

Assistant
python
import redis
import json
from functools import wraps

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

# Basic operations
r.set('user:1', json.dumps({'name': 'Alice'}), ex=3600)  # TTL 1 hour
user = json.loads(r.get('user:1'))
r.delete('user:1')

# Cache decorator
def cache(ttl=300):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            key = f"cache:{func.__name__}:{hash(str(args) + str(kwargs))}"
            cached = r.get(key)
            if cached:
                return json.loads(cached)
            result = func(*args, **kwargs)
            r.setex(key, ttl, json.dumps(result))
            return result
        return wrapper
    return decorator

@cache(ttl=600)
def get_user(user_id):
    return db.query("SELECT * FROM users WHERE id = %s", user_id)

# Cache-aside pattern
def get_product(product_id):
    key = f"product:{product_id}"
    cached = r.get(key)
    if cached:
        return json.loads(cached)
    product = db.get_product(product_id)
    r.setex(key, 300, json.dumps(product))
    return product

# Rate limiting
def is_rate_limited(user_id, limit=100, window=60):
    key = f"rate:{user_id}"
    current = r.incr(key)
    if current == 1:
        r.expire(key, window)
    return current > limit

# Pub/Sub
r.publish('notifications', json.dumps({'event': 'order_created', 'id': 123}))

# Sorted sets (leaderboards)
r.zadd('leaderboard', {'Alice': 100, 'Bob': 85, 'Charlie': 95})
top10 = r.zrevrange('leaderboard', 0, 9, withscores=True)