Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Using Redis or Memcached for Caching in Flask


Introduction

Caching improves application performance by reducing redundant computations and database queries. Flask can integrate with caching systems like Redis or Memcached to store and retrieve data efficiently.

This article demonstrates step-by-step how to implement caching using Redis or Memcached in a Flask application.

Step 1: Setting Up Flask and Installing Dependencies

Install Flask and a caching library like Flask-Caching and either Redis or Memcached:

            pip install flask flask-caching redis
        

If using Memcached, install the pymemcache library:

            pip install pymemcache
        

Step 2: Setting Up Redis or Memcached

Install and start the caching service on your system:

For Redis:

            sudo apt update
            sudo apt install redis
            sudo systemctl start redis
        

For Memcached:

            sudo apt update
            sudo apt install memcached
            sudo systemctl start memcached
        

Step 3: Configuring Flask-Caching

Update your Flask application to include caching:

            from flask import Flask
            from flask_caching import Cache

            app = Flask(__name__)

            # Configure caching
            app.config['CACHE_TYPE'] = 'RedisCache'  # Use 'MemcachedCache' for Memcached
            app.config['CACHE_REDIS_HOST'] = 'localhost'
            app.config['CACHE_REDIS_PORT'] = 6379
            cache = Cache(app)
        

Step 4: Adding Cache to Your Routes

Use the @cache.cached decorator to cache specific routes:

            @app.route('/')
            @cache.cached(timeout=60)
            def home():
                import time
                time.sleep(2)  # Simulate a slow computation
                return "Welcome to the cached Flask app!"
        

This caches the response for 60 seconds, reducing the computation time for repeated requests.

Step 5: Using Low-Level Cache Functions

Manually store and retrieve data using the cache object:

            @app.route('/store')
            def store_data():
                cache.set('key', 'value', timeout=300)  # Cache for 5 minutes
                return "Data cached successfully!"

            @app.route('/retrieve')
            def retrieve_data():
                value = cache.get('key')
                return f"Cached value: {value}"
        

Step 6: Verifying the Cache

Test your application to ensure caching works as expected. Use Redis or Memcached monitoring tools to confirm data storage.

For Redis:

            redis-cli
            KEYS *
        

For Memcached:

            telnet localhost 11211
            stats items
        

Step 7: Clearing the Cache

Clear the entire cache when needed:

            cache.clear()
        

Conclusion

By integrating Redis or Memcached with Flask, you can significantly enhance the performance of your application by caching frequently accessed data. This reduces the load on your database and speeds up responses.

Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java