Last active
December 16, 2024 10:44
-
-
Save Attumm/f07583b4a34df3dc203475bfa2a260b1 to your computer and use it in GitHub Desktop.
Redis-dict as cache for flask
This file contains hidden or 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 flask import Flask, jsonify | |
from redis_dict import RedisDict | |
from functools import wraps | |
import time | |
app = Flask(__name__) | |
# Initialize Redis dictionary for caching with default expiry of 5 minutes | |
cache = RedisDict(host='localhost', port=6379, db=0, namespace='mycache') | |
def cache_with_custom_expiry(expires_after=300): # Default 5 minutes cache | |
def decorator(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
cache_key = f"{func.__name__}:{str(args)}:{str(kwargs)}" | |
with cache.expire_at(expires_after): | |
try: | |
return cache[cache_key] | |
except KeyError: | |
result = func(*args, **kwargs) | |
cache[cache_key] = result | |
return result | |
return wrapper | |
return decorator | |
# Example expensive operation | |
def expensive_operation(n): | |
"""Simulate an expensive operation""" | |
time.sleep(2) # Simulate processing time | |
return n * n | |
@app.route('/compute/<int:number>') | |
@cache_with_custom_expiry(expires_after=30) # Cache for 30 seconds | |
def compute(number): | |
result = expensive_operation(number) | |
return jsonify({ | |
'number': number, | |
'result': result, | |
'cached': False | |
}) | |
@app.route('/cache/stats') | |
def cache_stats(): | |
return jsonify({ | |
'cache_size': len(cache), | |
'cache_keys': list(cache.keys()) | |
}) | |
@app.route('/cache/clear') | |
def clear_cache(): | |
cache.clear() | |
return jsonify({ | |
'message': 'Cache cleared', | |
'status': 'success' | |
}) | |
if __name__ == '__main__': | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment