python flask cache example

hljs.initHighlightingOnLoad();

Python Flask Cache Example

When developing web applications, caching is an important aspect to consider for performance optimization. Caching can help reduce the server load and improve response time for frequently accessed data.

Using Flask-Caching

Flask-Caching is a simple caching extension for Flask that provides caching support for various cache providers like Redis, Memcached, etc. Let's see an example of using Flask-Caching with Redis as the cache provider.


from flask import Flask
from flask_caching import Cache
  
app = Flask(__name__)
  
# Cache configuration
cache_config = {
    'CACHE_TYPE': 'redis',
    'CACHE_REDIS_URL': 'redis://localhost:6379/0'
}
  
# Initializing cache
cache = Cache(app, config=cache_config)
  
# Caching a function using cache.memoize decorator
@cache.memoize(timeout=60)
def expensive_function(arg):
    # Some expensive computation here
    return result
  
# Using the cached function
result = expensive_function(arg)
		

In the above example, we have configured Flask-Caching to use Redis as the cache provider and initialized the cache object with the app and cache configuration. We have used the @cache decorator to cache the expensive function for 60 seconds.

Using Flask-Cache

Flask-Cache is another caching extension for Flask that provides caching support for various cache providers like Redis, Memcached, etc. Let's see an example of using Flask-Cache with Redis as the cache provider.


from flask import Flask
from flask_cache import Cache
  
app = Flask(__name__)
  
# Cache configuration
cache_config = {
    'CACHE_TYPE': 'redis',
    'CACHE_REDIS_URL': 'redis://localhost:6379/0'
}
  
# Initializing cache
cache = Cache(app, config=cache_config)
  
# Caching a function using cache.cached decorator
@cache.cached(timeout=60)
def expensive_function(arg):
    # Some expensive computation here
    return result
  
# Using the cached function
result = expensive_function(arg)
		

In the above example, we have configured Flask-Cache to use Redis as the cache provider and initialized the cache object with the app and cache configuration. We have used the @cache decorator to cache the expensive function for 60 seconds.