能否脱离Flask应用使用Flask-Cache为普通函数实现缓存?
Absolutely! You can absolutely use Flask-Cache’s (now officially renamed Flask-Caching) familiar decorator-based caching for regular Python functions outside a Flask app—you just need to adjust the setup slightly since it’s built with Flask integration in mind, but it’s totally straightforward.
Step 1: Install Required Packages
First, make sure you have Flask-Caching and the Redis client installed:
pip install flask-caching redis
Step 2: Initialize the Cache Without a Flask App
Instead of passing a Flask app to the Cache constructor, you can initialize it with a standalone configuration. For Redis, you’ll need to set CACHE_TYPE to 'RedisCache' (the 'simple' type you used is an in-memory cache that won’t work with Redis) and provide your Redis server details.
Step 3: Apply the Cache Decorator to Regular Functions
Once the cache is set up, you can use the @cache.cached() decorator just like you would in a Flask app. For functions with arguments, use query_string=True to ensure the cache key includes the function parameters (so different inputs get different cached results).
Working Example Code
from flask_caching import Cache from datetime import datetime # Initialize cache with Redis configuration cache = Cache(config={ 'CACHE_TYPE': 'RedisCache', 'CACHE_REDIS_HOST': 'redis_server', # Replace with your Redis host 'CACHE_REDIS_PORT': 6379, # Default Redis port 'CACHE_REDIS_DB': 0, # Default Redis database # Optional: Add password if your Redis instance requires authentication # 'CACHE_REDIS_PASSWORD': 'your_redis_password' }) # Sample data store data = { datetime(2024, 5, 20): "Data for May 20", datetime(2024, 5, 21): "Data for May 21" } @cache.cached(query_string=True) # Include function args in the cache key def get_data_function(timestamp: datetime): print("Fetching fresh data...") # Only prints on cache misses return data.get(timestamp, "No data found") # Test the cached function if __name__ == "__main__": # First call: fetches fresh data and caches it print(get_data_function(datetime(2024, 5, 20))) # Second call: returns cached data (no "Fetching fresh data..." message) print(get_data_function(datetime(2024, 5, 20))) # Different timestamp: triggers a fresh fetch print(get_data_function(datetime(2024, 5, 21)))
Key Notes
- Cache Key Handling:
query_string=Trueis critical for functions with arguments—it generates unique cache keys based on input parameters. If you prefer more control, you can use thekey_prefixparameter to customize cache keys manually. - Cache Type Difference: The
'simple'cache type is a single-process in-memory cache. For Redis, always use'RedisCache'(some older versions accept'redis'as an alias). - Standalone Compatibility: Flask-Caching doesn’t strictly require a Flask app—initializing it with just a config dictionary lets you use it in any Python environment, not just Flask apps.
内容的提问来源于stack exchange,提问作者dl.meteo

