SoFunction
Updated on 2025-03-02

Detailed explanation of how to use Flask-Cache cache to speed up Flask

This article describes the method of using Flask-Cache cache to speed up Flask. Share it for your reference, as follows:

Django can be used to cache applications very conveniently, so what should I do if I don’t prepare so thoroughly in Flask? Make your own wheels? No, the former planted trees and then enjoyed the shade. We have Flask-Cache, which is as convenient as Django!

1. Installation

pip install Flask-Cache

2. Configuration

With my project (Source code) As an example:

existIn it, set the simple cache type, you can also use third-party redis, just like Django, just install redis and change the settings.

class Config:
  #Omitted  CACHE_TYPE = 'simple'

existapp/in

from flask_cache import Cache
#cachecache = Cache()
def create_app(config_name):
  app = Flask(__name__)
  #A few words are omitted here  cache.init_app(app)
  #Factory function returns the created program example  return app

3. Application

existin

from .. import db, cache
from . import main
from ..decorators import admin_required, permission_required
@('/', methods=['GET','POST'])
@(timeout=300,key_prefix='index')#Set a key_prefix as a tag, and then call ('index') in the content update function to delete the cache to ensure that the content accessed by the user is the latestdef index():
    print("I just called this function and didn't go to cache, but if I didn't go to cache, if I didn't go to cache, I just went to cache but didn't go to cache")
  # Omitted  return render_template('', form=form, posts=posts,show_followed=show_followed, pagination=pagination)

Execute it and see if there is anyprintOutput to see if the cache is in effect

4. Clear the cache

The first method is to set the expiration time to automatically clear it. You can add configuration items to Flask's config:

CACHE_DEFAULT_TIMEOUTOr add parameters to the decoratortimeout=50

The second method is to actively delete it, for example@(timeout=300,key_prefix='index')Set up the cache and use it when deleting it('index')Just

@('/askquestion', methods=['GET','POST'])
@login_required
def askquestion():
  #Ask questions and write database operations omitted  ('index')#Delete the cache  return render_template('', form=form, posts=posts,show_followed=show_followed, pagination=pagination)

Just like if the key is not set above, the default one iskey_prefix='view/%s',this%sIt's the request path, so if@(timeout=300)Create a cache to use('view//')Let's clear the cache, there are some functions in the request path, so it's best to set the key to do it.

There is also a way to clear all caches()

I hope that the description in this article will be helpful to everyone's Python programming based on the Flask framework.