Open In App

When should Flask.g be used

Last Updated : 25 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Consider yourself developing a web application in Flask and have a situation where you want particular data to be shared among a set of functions, now one way to get around this is by passing that data as a function argument. But this can lead to a lot of repeated work which is not a good development practice and will lead to code duplication. Another way or the recommended way of dealing with the above condition is to use a `flask. g` object which is a built-in Flask object. `flask. g ` is a global object provided by Flask which can be used to store data and it will be available throughout the lifespan of a single request.

In this article, we will answer questions like when to use the `flask. g` object, but before moving to that let me give you a short overview of Flask. Flask is a popular Python web framework written in Python with the motive of making the web application development process quicker with minimal boilerplate code. It is flexible, simple to use, and well-suited for small to medium size projects.

What is the Flask.g Module in Flask

The G module or Flask.g is provided by Flask which is used as a global object while developing a Flask app by developers to store and access data or any global variable in the context of the Flask app or a single request.

When `flask.g` Should be used

As we discussed in the introduction g variable provided by Flask can be used as a context for a request in routes in a  Flask app. But here are some common scenarios where `flask.g` should be used,

  1.  You can use flask.g to store connection or session data for each request you require access to the database so that it is available at any time when your Flask application is connected to some database. 
  2. The situation in which we need to share certain configuration variables as part of the request can be another use case. 
  3. If you want to keep some users’ data or passwords that are loaded on many requests for user information, “flask.g” is very useful.

Now that you know what “flask.g” is, let me walk you through a quick demonstration of how to create, store, and access ‘flask.g’ variables using the Flask app. I’m going to use FlaskHTTPAuth, an extension that provides us with a template for HTTP authentication for routes on Flask.

Implementation of Flask.g

Before moving directly to code implementation using a dedicated Python development environment is recommended which can be created as follow:

Setup a Development Environment

This step can be skipped but it is always a good idea to use a dedicated development environment for each project, this can be achieved using a Python virtual environment. To create one just run the following commands:

$ mkdir python_web_app; cd python_web_app

This will create a dedicated folder for the project, you can name it anything you want and cd (change directory) to go into your newly created directory then run the following command that will create a virtual environment for your project.

$ python3 -m venv venv
$ ls

Now let’s activate the virtual environment and start using it.

$ .\venv\Scripts\activate

Output:

 

By now you will have a virtual environment ready to be used, so let’s install Flask and flask_httpauth that provide us with the HTTP authentication features.

$ pip install flask flask_httpauth

Creating a Flask App

In this demonstration, we are going to create a Flask app with a few routes authenticated using the flask_httpauth library but first, let’s create a starter app for that create a file name main.py and add the following source code to it,

Python3




# Flask App
 
from flask import Flask
 
app = Flask(__name__)
 
@app.route('/')
def index():
  return "Hello World"
 
if __name__ == '__main__':
  app.run(debug=True)


As you can see it is a very simple HelloWorld Flask app with just a single route.

Output:

 

 

Using `flask.g` in the Flask App

We’ve initiated the development of the Auth Flask app by creating an auth instance of the HTTPBasicAuth which provides us with a basic authentication feature for the routes in the Flask App. Now let’s continue developing the app by adding routes and consuming the auth instance.

Python3




# In same main.py file
# import flask, flask_httpauth and g
from flask import Flask, g
from flask_httpauth import HTTPBasicAuth
 
# create a flask app
app = Flask(__name__)
 
# create a flask_httpauth object
auth = HTTPBasicAuth()
 
if __name__ == '__main__':
  app.run()


Now, The updated source code consists of 2 routes first the root route where we will log in and store the user in the `g` variable and second `/current_user` which returns the access to the stored user from the g variable.

The source code consists of a `verify_password` function that authenticates the user before rendering the route as shown below, if the user enters the correct credentials he is considered an authenticated user and given access to the routes specified.

Python3




# In same main.py file
# import flask, flask_httpauth and g
from flask import Flask, g
from flask_httpauth import HTTPBasicAuth
 
# create a flask app
app = Flask(__name__)
 
# create a flask_httpauth object
auth = HTTPBasicAuth()
 
# Authentication route for user,admin
@auth.verify_password
def verify_password(username, password):
  if username == 'admin' and password == 'password':
      g.user = username
      return True
  return False
 
# This is an authecated route login is required by admin user
# Decorator to check if user is logged in
@app.route('/')
@auth.login_required
def index():
  return f'This is an authecated route logged in by user,{g.user}'
 
# Return current logged in user
@app.route('/current_user')
@auth.login_required
def get_current_user():
  return f"Current logged in user is {g.user}"
 
if __name__ == '__main__':
  app.run()


Output:

When should Flask.g be used?

 

Once authenticated the username of the user is stored in the `g.user` variable and it is then used in the index() and get_current_user routes. The benefit of storing the username in the g object here is that we can access it in any route without passing it as a parameter to the function as it is available throughout the request context.

As you can see username accessed by `/` route

Output:

When should Flask.g be used?

 

As you can see username accessed by `/current_user` route

Output:

When should Flask.g be used?

 

In conclusion `flask. g` is a powerful tool for sharing data in a request context in Flask. But we should use it sparingly as storing too much data could lead to a reduction in the performance of the web application. Another thing is `flask.g` should be avoided in multithreaded applications as it is not thread-safe. 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads