What is the g object in this Flask code?

Question:

I found this code that times each response, but I’m not sure where g is supposed to come from. What is g?

@app.before_request
def before_request():
  g.start = time.time()

@app.teardown_request
def teardown_request(exception=None):
    diff = time.time() - g.start
    print diff
Asked By: Greg

||

Answers:

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"))

An app context lasts for one request / response cycle, g is not appropriate for storing data across requests. Use a database, redis, the session, or another external data source for persisting data.


Note that the dev server and any web server will output timing information in the logs already. If you really want to profile your code, you can use the Werkzeug application profiler.

Answered By: davidism
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.