app-generator / docs

App Generator - The Official Documentation | AppSeed
https://docs.appseed.us
1 stars 1 forks source link

Flask-Caching #84

Open mahfujul-helios opened 8 months ago

mahfujul-helios commented 8 months ago

Flask-Caching

Flask-Caching is a Flask extension that provides caching support for Flask applications. It allows developers to cache the results of expensive operations, such as database queries or API calls, to improve performance and reduce response times. Here's an overview of Flask-Caching:

Features:

  1. Decorator-Based Caching: Flask-Caching allows developers to cache the return value of a function using simple decorators. By decorating a Flask route or any other function, developers can cache its return value based on various parameters such as function arguments, URL parameters, or custom keys.

  2. Flexible Cache Backends: Flask-Caching supports multiple cache backends, including in-memory caching, filesystem caching, Redis caching, and Memcached caching. Developers can choose the cache backend that best suits their application's requirements and performance characteristics.

  3. Cache Expiration and Invalidation: Flask-Caching provides options for setting cache expiration times and invalidating cached data based on time intervals or specific events. This allows developers to control how long cached data remains valid and when it needs to be refreshed or invalidated.

  4. Cache Control Headers: Flask-Caching includes support for cache control headers, allowing developers to control caching behavior at the HTTP level. It provides utilities for setting cache-related headers such as Cache-Control, Expires, Last-Modified, and ETag to control caching behavior in web browsers and intermediate caching proxies.

  5. Memoization and Memoized Functions: Flask-Caching supports memoization, a technique for caching the return value of a function based on its input parameters. Developers can use the @memoize decorator to cache the return value of a function based on its arguments, improving performance by avoiding redundant calculations.

  6. Cache Partitioning and Namespaces: Flask-Caching provides support for cache partitioning and namespaces, allowing developers to organize cached data into separate logical groups or namespaces. This enables finer-grained control over cache management and helps avoid conflicts between different cached data sets.

  7. Integration with Flask Extensions: Flask-Caching integrates seamlessly with other Flask extensions and features, including Flask-SQLAlchemy, Flask-RESTful, Flask-Login, and Flask-RESTful. It provides utilities for caching database queries, API responses, user sessions, and other application data with minimal configuration.

Advantages:

Conclusion:

Flask-Caching is a valuable tool for optimizing the performance and scalability of Flask applications. By caching frequently accessed data, Flask-Caching reduces response times, conserves backend resources, and improves overall system performance. Whether you're building a simple web application or a complex API, Flask-Caching offers the features and flexibility you need to implement caching effectively and improve the performance of your Flask applications.

mahfujul-helios commented 8 months ago

Flask-Caching

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:

Disadvantages:

Examples

Let us discuss examples of Flask cache.

Example #1

Installing the Flask cache extension through any terminal

Syntax:

pip install Flask-Caching

Output:

fl

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:

f1

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.