Google News
logo
Flask - Interview Questions
What is g in python flask?
g is an object provided by Flask. It is a global namespace for holding any data you want during a single app context. For example, a before_request handler could set g.user, which will be accessible to the route and other functions.
 
from flask import g
@app.before_request
def load_user():
    user = User.query.get(request.session.get("user_id"))
    g.user = user

@app.route("/admin")
def admin():
    if g.user is None or not g.user.is_admin:
        return redirect(url_for("index"))

 

Advertisement