Updated April 19, 2023
Definition of Flask Cache
Flask cache is defined as a technique in flask utility that allows the user to store the result of an operation, which might take a huge amount of time in re-running the operation or in other words the execution of the operation is expensive to perform again and again. This operation in general is a function call. With this “storage” of the result post caching when the operation is performed again the answer is pulled out of the storage instead of the actual execution of the operation. This utility is an extension to Flask that adds support of caching for flask applications at the backend. One major thing to keep in mind is that when thing runs slow, use some caches!
Syntax:
Below we will first go through some important syntax that will enable us to perform the tasks which are equally important as understanding the working of cache in Flask.
Installing the Flask cache extension through any terminal:
easy_install Flask-Caching
OR
pip install Flask-Caching
Importing the cache module of Flask in a python code:
from flask_caching import Cache
cache = Cache(config={'CACHE_TYPE': <select choice from list of types>})
Capability of caching view function using @cached decorator:
@cache.cached(timeout=27)
def index():
return render_template(<html page>)
Capability of caching other function using @cached decorator:
@cache.cached(timeout=50, key_prefix='custom_func')
def custom_list_function():
variable = function_name()
return [random.randrange(0, 1) for x in range(2709)]
cached_list = custom_list_function()
Caching Data Explicitly:
cache.set (*args, **kwargs)
Clearing cached Data:
cache.clear()
How does cache work in Flask?
Now that we know how a typical structure of a cache process in Flask would look like it is now equally important to understand the working behind the flask cache and what happens in different functionality of usage of cache in Flask.
Cache is managed through an instance that is declared in the code. Also, users can easily et up the instance of Cache later in the code using the init_app method. Now in order for caching to work, specification of the cache type is important because it will enable the type of caching object that needs to be used in flask cache. By default, we have null, which means that there will be no cache until and unless specified. There are various other types of cache present and the most widely used is the simple cache method and other than that one may use as per the desirability of the app that is being developed using flask. Once the cache type is imported as a string, it will be then instantiated. Finally, the return of this import object will be a cache object complying to the cache API. At this point, the instance of cache is created along with the cache type. Post this one can use the instance of cache as per the requirement of the application development at hand.
Now, we will start discussing another extension to what we learned earlier about cache instantiation. Once the object is instantiated, we can use the concept of decorators to cache functions. Caching is done for view function in a certain way and for other functions, we need to incorporate an argument namely, key_prefix. The important point to understand here is what does key_prefix do in the working of the cache. Key_prefix is used for the generation of a key for the value which has been cached. But why is this argument even used? What is the role which this argument plays? Simply put it differentiates view function from other functions. To understand it in detail, we look at the following example. Supposedly there are 2 functions that calls the same function which consists of the cache. Now there is a possibility of the cached value to be overwritten since there is no key associated. That is exactly what key_prefix does. It maintains a key-value mapping pair with key being maybe the name of the function or something which resembles the function from which another function that consists of caching is called from and the value being the result of the function. Next time anywhere the same cache_key is called, flask knows what value to present.
Now the next part of understanding working of cache is to know how to clear the cache if required. This is very helpful in cases of more than normal memory utilization. Using the clear function to the cache, we can flush out the data stored in that instance. This is very much required once when the code finishes executing. One thing to keep in mind is that completely clearing off cache might not be supported by some backend implementation and in some cases not using a key prefix might flush off the whole database!
With understanding how instantiation is done, what role does an important argument play in deciding how cache will be managed we now have a complete picture of working of cache?
Advantages and disadvantages
In this section, we will look at different advantages and disadvantages of caching in flask.
Advantages:
- Caching helps in speeding up the process of loading in web development so that the response time in a web application can be reduced.
- As a result of using cache in a web application, the resources used in loading a page is reduced and hence these resources are available to take up other commands.
- Repeated interaction with 3rd party sources in an application is minimized and hence the dependency is reduced leading to a more robust web application.
- The network traffic is highly reduced and as a result the network congestion
Disadvantages:
- In cases of lack of proper proxy update, stale data might exist in the application.
- Implementation of cache increases the complexity as purging of the cache is an absolute necessity.
Examples
Let us discuss examples of Flask cache.
Example #1
Installing the Flask cache extension through any terminal
Syntax:
pip install Flask-Caching
Output:
Example #2
Importing the cache module of Flask in a python code:
Syntax:
from flask import Flask
from flask_caching import Cache
cache = Cache(config={'CACHE_TYPE': 'simple'})
Output:
Conclusion
In this article, we have got a flavor of all the nitty-gritties of Flask cache, and one special thing on why do we need Flask cache is that the micro-framework Flask doesn’t have a built-in cache functionality and hence the requirement of this utility! Using the advantages and disadvantages listed, taking a decision of the usage will surely be useful.
Recommended Articles
This is a guide to Flask Cache. Here we discuss the definition, How does cache work in Flask?, Advantages and disadvantages, and examples. You may also have a look at the following articles to learn more –