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 )