无法在视图函数中的2个烧瓶请求之间共享变量 [英] Unable to share variables between 2 flasks requests in a view function

查看:95
本文介绍了无法在视图函数中的2个烧瓶请求之间共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要在2个烧瓶请求之间共享一个变量! 该变量是一个大熊猫数据框.

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'

,但这总是返回失败,即:None

当我在这里阅读文档时,说的是:

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

从Flask 0.10开始,此文件存储在应用程序上下文中, 不再位于请求上下文中,这意味着 仅绑定了应用程序上下文,尚未绑定请求.

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?

任何帮助将不胜感激

推荐答案

链接的答案似乎是完全错误的. g对象用于在同一请求内将全局功能数据从一个功能存储到另一个 ,根本不用于在请求之间共享数据.

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.

为此,您需要会话:

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个烧瓶请求之间共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆