Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the g object in this Flask code?

Tags:

python

flask

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 
like image 408
Greg Avatar asked May 28 '15 18:05

Greg


People also ask

What is the G object in Flask?

g is an object for storing data during the application context of a running Flask web app. g can also be imported directly from the flask module instead of flask. globals , so you will often see that shortcut in example code.

What is the G object in Flask how does it differ from the session object?

session gives you a place to store data per specific browser. As a user of your Flask app, using a specific browser, returns for more requests, the session data is carried over across those requests. g on the other hand is data shared between different parts of your code base within one request cycle.

What is __ name __ In Flask?

__name__ is just a convenient way to get the import name of the place the app is defined. Flask uses the import name to know where to look up resources, templates, static files, instance folder, etc.

What is Appcontext in Flask?

The application context is a good place to store common data during a request or CLI command. Flask provides the g object for this purpose. It is a simple namespace object that has the same lifetime as an application context.


1 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.

like image 118
davidism Avatar answered Sep 20 '22 00:09

davidism