Explain how to speed up Flask using Flask Cache cache

  • 2021-06-28 09:25:16
  • OfStack

This article provides an example of how to speed up Flask using the Flask-Cache cache.Share it for your reference, as follows:

Django has a convenient application cache, so what if Flask is not so well prepared?Do you make your own wheels?No, we have Flask-Cache, which is as convenient to use as one inside Django.

1. Installation


pip install Flask-Cache

2. Configuration

Take my zhihu project (source code) for example:

In config.py, you can set the simple cache type, or you can use a third-party redis like Django1, just install the redis change settings


class Config:
  # ellipsis 
  CACHE_TYPE = 'simple'

Inside app/init.py


from flask_cache import Cache
# cache 
cache = Cache()
def create_app(config_name):
  app = Flask(__name__)
  # Omit a few words here 
  cache.init_app(app)
  # Factory function returns an example of the created program 
  return app

3. Application

Inside views.py


from .. import db, cache
from . import main
from ..decorators import admin_required, permission_required
@main.route('/', methods=['GET','POST'])
@cache.cached(timeout=300,key_prefix='index')# Set up 1 individual key_prefix To be tagged and then called in a function with updated content cache.delete('index') To delete the cache to ensure that the content accessed by the user is up to date 
def index():
    print(" Show me on the command line that I just called this function without going through the cache or that I just went through the cache without using the function ")
  #  ellipsis 
  return render_template('index4.html', form=form, posts=posts,show_followed=show_followed, pagination=pagination)

Execute once to see if there is any print Output, you can see if the cache is valid

4. Clear Cache

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

CACHE_DEFAULT_TIMEOUT or Decorator Plus Parameters timeout=50 .

The second way is to actively delete, for example @cache.cached(timeout=300,key_prefix='index') Cache set up for deletion cache.delete('index') that will do


@main.route('/askquestion', methods=['GET','POST'])
@login_required
def askquestion():
  # Question Writing to Database Operation Omitted 
  cache.delete('index')# Delete Cache 
  return render_template('askquestion.html', form=form, posts=posts,show_followed=show_followed, pagination=pagination)

As above, if key is not set, the default is key_prefix='view/%s' , this %s Is the requested path request.path So if you use @cache.cached(timeout=300) Create a cache to use cache.delete('view//') To clear the cache, some functions of the request path do not exist, it is best to set key to do so

There is also one way to clear all caches cache.clear()

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


Related articles: