【问题标题】:Flask : RuntimeError: Working outside of request context烧瓶:RuntimeError:在请求上下文之外工作
【发布时间】:2021-08-09 19:21:01
【问题描述】:

我正在开发一个 Flask 程序,并想在函数外部使用一个变量(存在于函数内部)。

所以,我研究并偶然发现了 sessinos 存储。我用它来存储我的变量并在函数外使用它。

但是我收到了这个错误

RuntimeError:在请求上下文之外工作。

这通常意味着您尝试使用以下功能 需要一个活动的 HTTP 请求。查阅有关测试的文档 有关如何避免此问题的信息。

这是 app.py 的代码:

from flask import Flask, render_template, request, session

app = Flask(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

@app.route('/', methods =["GET", "POST"])
def gfg():
    if request.method == "POST":
       first_name = request.form.get("fname")
       session['first_name'] = first_name
       return "Your name is " + first_name
    return render_template("index.html")

with app.app_context():
    first_name = session.get('first_name')
    print(first_name)
if __name__ == '__main__':
    app.run(debug=True)


【问题讨论】:

    标签: python function variables flask session


    【解决方案1】:

    我认为您尝试做的不是正确的方法。简单地说,你不能在 @app.route() 函数之外使用 session.anything,因为 session 需要一个正在处理的活动请求。

    但是,如果您想在由于某种原因没有活动请求的时候使用变量 first_name,您可以使用 python 全局:

    from flask import Flask, render_template, request, session
    app = Flask(__name__)
    app.secret_key = 'change_this! and dont include it in questions!'
    first_name = "nothing yet"  # this is the initial value when the app runs
    
    @app.route('/', methods =["GET", "POST"])
    def gfg():
        if request.method == "POST":
           global first_name  # this will use the global scope for this variable
           first_name = request.form.get("fname")  # this will update the global variable now!
    
           return "Your new name is " + first_name
        return "Your current name is " + first_name
    
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    【讨论】:

    • 嘿,谢谢。我试过这个,但它不工作。它仍在返回 first_name 的旧值,即“Nothing Yet”:(
    • 是的,那是因为“with app.app_context()”行仅在应用启动时运行一次。如果您创建第二条路线,例如 def fgf(): print(last_name),它将打印您在调用 gfg() 时设置的 last_name。 app.app_context 行仅在应用程序运行时使用,您需要稍后在至少调用 gfg() 一次之后使用该变量。
    • 我通过添加带有 url /print 的另一条路线使这一点更加清晰。如果您在该路线上获取或发布,它将打印 first_name 的最后一个已知值
    • 我在代码中添加了print(fgf()),但它返回无
    • 这也是在我在网页中输入之前发生的
    猜你喜欢
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多