Alex
Alex

Reputation: 5904

How to share session values created outside the context in Flask?

How do I store something created by a thread, in a session, so I can access that value later in another request?

Here is a sample:

@app.route('/one')
def one():
    @copy_current_request_context
    def x():
        session['status'] = "done"      

    t = threading.Thread(target=x)
    t.start()
    return "One"



@app.route('/two')
def two():
    status = session['status']
    return "Two: {}".format(status)

In example above I store the 'status' from within the thread (I need to run the thread) inside the /one request but later, let's say 5s, I want to check for the status in another request (/two).

Also does @copy_current_request_context make a read-only (or read and discard write) copy of the session/request?

Upvotes: 0

Views: 499

Answers (2)

Alex
Alex

Reputation: 5904

  1. By using the suggestion from @soroosh-khodami I was able to achieve what I wanted. Bellow is the code that can do that.

warehouse = {} # This associative array will keep the data

@app.route('/one')
def one():
    global warehouse
    @copy_current_request_context
    def x():
        warehouse['status'] = "done"      

    t = threading.Thread(target=x)
    t.start()
    return "One"



@app.route('/two')
def two():
    global warehouse
    status = warehouse['status']
    return "Two: {}".format(status)

Of course this is a naive implementation - as this object warehouse will be shared among all the requests and session - so a protection mechanism should be in place (Ex: 1.Store all things from a session under a certain key 2. Have a cleanup thread , etc)

Bonus: The addition to that is that is working even in non-dev environment (ex: Twisted server)

  1. Yes, @copy_current_request_context makes a read only copy of the context (as far as I tested)

Upvotes: 1

Soroosh Khodami
Soroosh Khodami

Reputation: 1333

The easiest and somehow best answer is using global variables that have been described completely Here.

But if your application is going to be scaled and you need this data to be shared with other instances, you might use "Redis" as a fast In-Memory DB. More details

Upvotes: 1

Related Questions