0
0
Flaskframework~30 mins

G object for request-scoped data in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Flask's g Object for Request-Scoped Data
📖 Scenario: You are building a simple Flask web app that needs to store and access data specific to each web request. This data should be available throughout the request but reset for the next request.
🎯 Goal: Learn how to use Flask's g object to store and access request-scoped data safely and easily.
📋 What You'll Learn
Create a Flask app with a route
Use the g object to store data during a request
Access the stored data later in the same request
Demonstrate that data is reset for each new request
💡 Why This Matters
🌍 Real World
Web apps often need to keep track of user info or other data during a single web request without mixing it with other requests. Flask's <code>g</code> object is perfect for this.
💼 Career
Understanding request-scoped data is essential for backend web development with Flask, helping you write clean, safe, and maintainable code.
Progress0 / 4 steps
1
Set up a basic Flask app with a route
Import Flask from flask and create a Flask app called app. Then define a route / with a function index that returns the string 'Hello, Flask!'.
Flask
Need a hint?

Start by importing Flask and creating an app instance. Then add a route decorator and a simple function that returns a greeting.

2
Import g and store data in it
Import g from flask. Inside the index function, set g.user to the string 'Alice' to simulate storing user data for this request.
Flask
Need a hint?

Remember to import g from flask. Then assign the user name to g.user inside the route function.

3
Access the stored g.user data in the response
Modify the index function to return a greeting that includes the user name stored in g.user. Use an f-string to return f'Hello, {g.user}!'.
Flask
Need a hint?

Use an f-string to include g.user in the returned string.

4
Add a before_request function to set g.user
Define a function load_user decorated with @app.before_request that sets g.user to 'Alice'. Remove the g.user assignment from the index function.
Flask
Need a hint?

Use @app.before_request to run code before each request. Set g.user there so it is available in all routes.