3

What I want is to share a variable between 2 flask requests! The variable is a large pandas dataframe.

I have read in this answer that i need to use g from flask global ! basically, I have 2 views function like this :

from flask import g
@home.route('/save', methods=['GET'])
def save_ressource():
    an_object = {'key': 'value'}
    setattr(g, 'an_object', an_object)
    return 'sucees'
@home.route('/read', methods=['GET'])
def read_ressource():
    an_object = getattr(g, 'an_object', None)
    if an_object:
        return 'sucess'
    else:
        return 'failure'

but this always return failure ie : None

and when i read in the documentation here it's said that :

Starting with Flask 0.10 this is stored on the application context and no longer on the request context which means it becomes available if only the application context is bound and not yet a request.

My question is how to solve this problem?

As said in the docs how can I bound application context?

Should I use sessions instead?

Any helps will be appreciate

Community
  • 1
  • 1
Espoir Murhabazi
  • 5,973
  • 5
  • 42
  • 73

1 Answers1

8

The linked answer appears to be completely wrong. The g object is for storing global data from one function to another within the same request, and is not at all for sharing data between requests.

For that you need sessions:

from flask import Flask, session

@home.route('/save', methods=['GET'])
def save_ressource():
    an_object = {'key': 'value'}
    session['an_object'] = an_object
    return 'sucees'

@home.route('/read', methods=['GET'])
def read_ressource():
    an_object = session.get('an_object')
    if an_object:
        return 'sucess'
    else:
        return 'failure'
ti7
  • 16,375
  • 6
  • 40
  • 68
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895