max
max

Reputation: 52323

What's the difference between current_app and g context variable?

Both current_app and g are application context variables, so they are loaded and unloaded with each request, so anything data stored on them will only be available within the same request.

The only difference I can see is that g starts empty at the beginning of each request, while current_app starts with some attributes (like config) that are copied from the application object. But that wouldn't justify having g object at all, since one could just as easily store new information on current_app.

What's the difference that I don't see?

Upvotes: 12

Views: 4641

Answers (2)

SeasonalShot
SeasonalShot

Reputation: 2579

From the documentation:

When the request starts, a RequestContext is created and pushed, which creates and pushes an AppContext first if a context for that application is not already the top context. While these contexts are pushed, the current_app, g, request, and session proxies are available to the original thread handling the request.

When you are on a browser and made your first request, the and application context is created and pushed out to the stack and then on the top of the stack, the request context are created and popped out. The point is - the application context is at the bottom of the request stack data structure.

More so on g: It's a namespace object that can store data during an application context. This is a good place to store resources during a request. g is a special object that is unique for each request. It is used to store data that might be accessed by multiple functions during the request. The connection is stored and reused instead of creating a new connection if get_db is called a second time in the same request. more: When should Flask.g be used?

Side note: Checkout the user for Context Processors (The dict returned by that, is available directly to all the templates )

Upvotes: 3

vishes_shell
vishes_shell

Reputation: 23524

I believe that you read the docs on g and on current_app. So what i could understand from it:

current_app:

Points to the application handling the request. This is useful for extensions that want to support multiple applications running side by side.

[emphasis mine]

So you are getting context of current app, while g stores everything, from source code:

def _lookup_app_object(name):
    top = _app_ctx_stack.top
    if top is None:
        raise RuntimeError(_app_ctx_err_msg)
    return getattr(top, name)

def _find_app():
    top = _app_ctx_stack.top
    if top is None:
        raise RuntimeError(_app_ctx_err_msg)
    return top.app

current_app = LocalProxy(_find_app)
g = LocalProxy(partial(_lookup_app_object, 'g'))

So if you're running several applications, current_app would reference to current one(obvious, right), and g to everything.

Upvotes: 8

Related Questions