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. 



Similar Reads

Documenting Flask Endpoint using Flask-Autodoc
Documentation of endpoints is an essential task in web development and being able to apply it in different frameworks is always a utility. This article discusses how endpoints in Flask can be decorated to generate good documentation of them using the Flask-Autodoc module. This module provides the following features - Helps to document endpoints of
4 min read
How to use Flask-Session in Python Flask ?
Flask Session - Flask-Session is an extension for Flask that supports Server-side Session to your application.The Session is the time between the client logs in to the server and logs out of the server.The data that is required to be saved in the Session is stored in a temporary directory on the server.The data in the Session is stored on the top o
4 min read
How to Integrate Flask-Admin and Flask-Login
In order to merge the admin and login pages, we can utilize a short form or any other login method that only requires the username and password. This is known as integrating the admin page and Flask login since it simply redirects users to the admin page when they log in. Let's is how to implement this in this article. Integrate Flask Admin and Fla
8 min read
Minify HTML in Flask using Flask-Minify
Flask offers HTML rendering as output, it is usually desired that the output HTML should be concise and it serves the purpose as well. In this article, we would display minification of output routes of Flask responses using the library - Flask-Minify. Advantages of MinificationWebsites load faster as fewer lines are there to upload and download.Ban
12 min read
Flask URL Helper Function - Flask url_for()
In this article, we are going to learn about the flask url_for() function of the flask URL helper in Python. Flask is a straightforward, speedy, scalable library, used for building, compact web applications. It is a micro framework, that presents developers, useful tools, and, features, for coding REST APIs, and backend data processing, of web apps
12 min read
Flask vs Django - Which Framework Should You Choose in 2024
Python isn't just a language; it's a powerhouse of tools that can make a developer's life a whole lot easier. And when it comes to building web applications, Flask and Django are two names that shine brightly. These frameworks are like toolboxes, filled with everything you need to create powerful, elegant web apps without getting bogged down in the
8 min read
Upload and Read Excel File in Flask
In this article, we will look at how to read an Excel file in Flask. We will use the Python Pandas library to parse this excel data as HTML to make our job easier. Pandas additionally depend on openpyxl library to process Excel file formats. Before we begin, make sure that you have installed both Flask and Pandas libraries along with the openpyxl d
3 min read
Python Flask - ImmutableMultiDict
MultiDict is a sub-class of Dictionary that can contain multiple values for the same key, unlike normal Dictionaries. It is used because some form elements have multiple values for the same key and it saves the multiple values of a key in form of a list. Example: C/C++ Code from werkzeug.datastructures import MultiDict orders = MultiDict([(1, 'GFG'
2 min read
Handling 404 Error in Flask
Prerequisite: Creating simple application in Flask A 404 Error is showed whenever a page is not found. Maybe the owner changed its URL and forgot to change the link or maybe they deleted the page itself. Every site needs a Custom Error page to avoid the user to see the default Ugly Error page. GeeksforGeeks also has a customized error page. If we t
4 min read
Python | Using for loop in Flask
Prerequisite: HTML Basics, Python Basics, Flask It is not possible to write front-end course every time user make changes in his/her profile. We use a template and it generates code according to the content. Flask is one of the web development frameworks written in Python. Through flask, a loop can be run in the HTML code using jinja template and a
3 min read
Article Tags :
Practice Tags :