Unable to share variables between 2 flasks requests in a view function [duplicate]

…衆ロ難τιáo~ 提交于 2020-08-08 14:53:00

问题


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


回答1:


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'


来源:https://stackoverflow.com/questions/48458322/unable-to-share-variables-between-2-flasks-requests-in-a-view-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!