Understanding ‘g’ and ‘session’ in Flask
Published: 2024-04-16 04:11:55

When you’re building a Flask web application, sometimes you run into situations where you have data that you’d like to store globally during a request or across multiple requests. This is where Flask’s built-in objects 'g' and 'session' can come in handy. In this blog post, we’ll explore what both of these objects are, similarities and differences, as well as when to use each one.

## **What is 'g'?**

In Flask, 'g' is used to temporarily store and share data across your app within the same request context. Here are some of the key characteristics of 'g':

**1. Does not persist between requests:**
A new instance of 'g' is created each time a client sends a request to a Flask application, so the data stored in 'g' is not persisted between different requests.

**2. Accessible across functions:**
The data stored in 'g' can be accessed from any function within the same request context, allowing you to share data between different parts of your app within the same request handling process.

**3. Automatically cleared at the end of each request:**
At the end of each request, Flask automatically clears 'g', removing any data stored within it. This helps to make sure the data in 'g' remains isolated and specific to the current request.

## **Use cases for 'g'**

In certain situations 'g' can be used to dry up your code. It is often used in request decorators like @app.before_request, @app.after_request and @app.teardown_request. For example you could use 'g' to set a flag at the beginning of a request and handle it at the end. It can also be used for resource management like managing database connections.

Here’s an example of how to use 'g' for managing a database connection from Flask’s [documentation](https://flask.palletsprojects.com/en/2.3.x/appcontext/) on 'g':


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mswx3x3wzmsij7vpw74.png)

The **get_db()** function checks if a database connection already exists in 'g'. If it does not, it establishes a new connection and stores it in g.db, that way any function during the request can reuse the same database connection. The **teardown_db()** function executes when the application context ends (after the response is constructed and sent). It ensures the cleanup of the database connection and removes the connection from 'g'. 

## **What is a ‘session’?**

In contrast to 'g', Flask’s 'session' object is used for storing data across requests. Here are some of the key characteristics of a 'session' object:

**1. Persists across requests**
The session object is designed to store data that needs to persist across multiple requests from the same user. When is session data typically cleared? If you’re using a session for user authentication and authorization, it’s typically cleared when a user logs out. You can also set expiration periods or timeouts for your sessions.

**2. Stored on the server**
Session data is stored on the server, however Flask uses client or server-side cookies to store the session identifier. Each time a request is sent to the server the client sends the cookie back to the server, the session ID is verified, and then the session data can be retrieved.

**3. Secure**
Flask secures the session data by signing it with a secret key, which helps prevent tampering. By managing sessions securely you can protect against vulnerabilities like session hacking.

 
The metaphor I like to think of when trying to understand the concepts of 'g' and 'session' is a locker at the gym. Your **gym session** represents the **request**. Each time you go to the gym you put your belongings in a **locker ('g')**. The locker you use is specific to your current gym session and allows you to store and access the **items (data)** that you need during your workout. When you’re done with your workout, you empty your locker in the same way that at the end of each request in Flask the 'g' object is cleared. In contrast, if you were to rent a gym **locker for a year**, the locker would represent a **session**. You’re able to continue to go back to your locker over multiple **gym sessions (requests)** to access the **items (data)** that you need.

## **Use cases for ‘session’**

‘Session’ is used for data that needs to persist across requests from the same user, such as user authentication and authorization, shopping carts, or user preferences. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pyhw4t6w2villsz0vpjf.png)

When a user successfully logs in, the user's ID and username are stored in the session object (session["user_id"] and session["username"]). By storing the user’s data in the session, we can securely persist the user’s identity across different requests within the same session. The logout method clears the session object by removing the user_id and username keys.

## **Summary**

To summarize, understanding Flask's 'g' and 'session' objects is essential for effective data management in web applications. ‘G’ provides temporary storage for data during a single request and is ideal for scenarios like database connection management. While ‘session’ stores data across requests and is useful for managing user data like authentication and authorization or shopping carts.


Sources
- [Flask Documentation: The Application Context](https://flask.palletsprojects.com/en/2.3.x/appcontext/)
- [GeeksForGeeks: When should Flask.g be used](https://www.geeksforgeeks.org/when-should-flask-g-be-used/)
- [Stack Overflow: When Should Flask.g be used?](https://stackoverflow.com/questions/15083967/when-should-flask-g-be-used)