In web applications, many times we use the same data again and again or calculations have to be repetitively performed when we visit certain pages. If we recompute them again or access the data from a slow database it can hamper the performance of our application. To overcome this problem we can use the caching
method. It may sound like a fancy term but I am sure you have used one or more of the following methods to achieve caching. Let’s discuss how we can implement caching in our applications. There are two ways we can store cache data - one at the client side and another at the server side.
We can use a Python dictionary to get the data in constant time instead of recomputing it. It has linear time complexity O(1). Let’s see its example -
1
2
3
4
5
phonebook = dict()
phonebook['James'] = 9453852201
phonebook['Rahul'] = 5956983692
print(phonebook['James'])
Flask provides a session object which is nothing but a dictionary. Here you can store frequently required application data. Let’s see how to implement it -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) app.secret_key = 'random_string’ @app.route('/') def index(): if 'username' in session: username = session['username'] return "Already logged in" else: return "Not logged in." @app.route('/login', methods = ['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) else: return render_template('login.html')
So far we’ve discussed client side data storage. Now take the scenario of an e-commerce shopping cart where you put some items in the cart and close the website. Later when you come back to complete the purchase you are supposed to see the same cart items. A user will not want to fill the cart again. For this purpose, we have to store the data on the server side using cache memory instead of a session variable on the client side. There are many databases to achieve this method like Redis, Memcache, MongoDB etc.
Redis is a cloud-based key/value storage. We can store our application data that we want to retrieve frequently on Redis memory. Redis is easy to implement and fast. You can find more details at this
For Python implementation, we need to install the Redis server in our local machine using the following command.
pip install redis
pip install redis-server
In the production environment, you can leverage the benefits of docker as it already has the Redis image implemented there. Apart from this, we can also use cloud-based alternatives like Google Cloud Platform or Microsoft Azure. They also provide Redis instances.
After installing redis-server
we need to run it in the terminal using -
redis-server
To leverage Redis in our web application (in this case Flask) we’ll use the Flask-Session
library.
pip install flask-session
Following is the implementation of Redis session.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
import os from flask import Flask, session, flash import redis from flask_session import Session app = Flask(__name__) # Configuration Variables app.config["DEBUG"] = True conn_redis = redis.from_url('redis://localhost:6379') sess = Session() sess.init_app(app) # to set a value session['key'] = 'value' # to get a value session, get('key')
Flask-Session extends the Flask session
object so it’ll work the same way that we saw earlier. We just need to configure it using the above code.
That’s all for now. I hope you like this article. Try to utilize one of these methods to improve the performance of your web application. Happy coding :)