Use a flask session inside a python thread
Question: How can I update a flask session inside a python thread? The below code is
throwing this error:

*** RuntimeError: working outside of request context

    
    
    from flask import session
    def test(ses):
        ses['test'] = "test"
    
    @app.route('/test', methods=['POST', 'GET'])
    def mytest():
        t = threading.Thread(target=test, args=(session, ))
        t.start()
    


Answer: When you execute `t.start()`, you are creating an independent thread of
execution which is _not synchronized with the execution of the main thread in
any way._

The Flask [`session` object](//flask.pocoo.org/docs/0.10/api/#flask.session)
is **only defined in the[context of a particular HTTP
request](//flask.pocoo.org/docs/0.10/reqcontext/)**.

What does the variable `session` **mean** in the second thread (`t`)?

When `t` executes, there is no guarantee that the user request from the main
thread still exists or is in a modifiable state. Perhaps the HTTP request has
already been fully handled in the main thread.

Flask detects that you are trying to manipulate an object that is dependent on
a particular context, and that your code is not running in that context. So it
raises an exception.

There are a variety of approaches to synchronizing output from multiple
threads into a single request context but... **what are you actually trying to
do here?**

