Flask G variable Simple example
<p>From what i understand a g variable is a temporary storage that last form one single request to the other. For example i was thinking it should work like this. But i can seem to get it to work.</p>

<pre><code>from flask import Flask, g, redirect, url_for
    app = Flask(__name__)

    @app.route('/')
    def hello_world():
        g = "hello world"
        return redirect(url_for('test'))

    @app.route('/test')
    def test():
        return str(g)

    if __name__ == "__main__":
        app.run(debug=True)
</code></pre>

<p>Flask <code>g</code> is available in application context and lasts for the lifetime of the request.</p>

<p><code>What is application context?</code></p>

<p>As cited on <a href="http://flask.pocoo.org/docs/0.11/appcontext/" rel="nofollow">Application Context Page</a>, flask app is in many states while being executed.</p>

<blockquote>
  <p>One of the design ideas behind Flask is that there are two different âstatesâ in which code is executed. The application setup state in which the application implicitly is on the module level. It starts when the Flask object is instantiated, and it implicitly ends when the first request comes in. While the application is in this state a few assumptions are true:</p>
  
  <ul>
  <li>the programmer can modify the application object safely.</li>
  <li>no request handling happened so far</li>
  <li>you have to have a reference to the application object in order to modify it, there is no magic proxy that can give you a reference to the application object youâre currently creating or modifying.</li>
  </ul>
  
  <p>In contrast, during request handling, a couple of other rules exist:</p>
  
  <ul>
  <li>while a request is active, the context local objects (flask.request and others) point to the current request.</li>
  <li>any code can get hold of these objects at any time.</li>
  </ul>
  
  <p>There is a third state which is sitting in between a little bit. Sometimes you are dealing with an application in a way that is similar to how you interact with applications during request handling; just that there is no request active. Consider, for instance, that youâre sitting in an interactive Python shell and interacting with the application, or a command line application.</p>
</blockquote>

<p>So, basically while you run the app, it exits in many states.</p>

<p>Example : One is serving your requests, one is watching the files for reloading.</p>

<p>If you ever use <a href="http://www.celeryproject.org/" rel="nofollow">Celery</a>, then you would have to run it in separate application context. That is when role of <code>g</code> comes into play. 
One very common use of celery is to send mails asynchronously.
Imagine you catch a request and after processing it you need to send a mail.
You can store the user information in <code>g</code> to be passed to celery.</p>

python flask