无法在视图函数中的 2 个烧瓶请求之间共享变量
Unable to share variables between 2 flasks requests in a view function
我想要的是在2个烧瓶请求之间共享一个变量!
该变量是一个大 pandas 数据框。
我已阅读 that i need to use g from flask global!
基本上,我有 2 个这样的视图功能:
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'
但这总是return失败即:None
当我在这里阅读文档时说:
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.
我的问题是如何解决这个问题?
如文档中所述,我如何绑定应用程序上下文?
我应该改用会话吗?
任何帮助将不胜感激
链接的答案似乎完全错误。 g
对象用于在同一请求 中将全局数据从一个函数存储到另一个函数,根本不用于在请求之间共享数据。
为此你需要 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'
我想要的是在2个烧瓶请求之间共享一个变量! 该变量是一个大 pandas 数据框。
我已阅读
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'
但这总是return失败即:None
当我在这里阅读文档时说:
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.
我的问题是如何解决这个问题?
如文档中所述,我如何绑定应用程序上下文?
我应该改用会话吗?
任何帮助将不胜感激
链接的答案似乎完全错误。 g
对象用于在同一请求 中将全局数据从一个函数存储到另一个函数,根本不用于在请求之间共享数据。
为此你需要 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'