Junior — Middle
Have you had experience working with the global flask.g object in your projects?
sobes.tech AI
Answer from AI
flask.g is a global object in Flask used to store data specific to the current request. It exists only within the context of a single request and allows convenient passing of information between functions and handlers without using global variables.
For example, you can store a database connection in flask.g to use it in different parts of the handler:
from flask import Flask, g
import sqlite3
app = Flask(__name__)
def get_db():
if 'db' not in g:
g.db = sqlite3.connect('database.db')
return g.db
@app.route('/')
def index():
db = get_db()
# use db for queries
return 'Hello'
@app.teardown_appcontext
def close_db(exception):
db = g.pop('db', None)
if db is not None:
db.close()
Thus, flask.g helps store and manage resources related to the current request.