跨 Flask 路由使用变量 [英] Using variables across Flask routes

查看:18
本文介绍了跨 Flask 路由使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Flask 并且有一个关于在路由上下文中使用变量的问题.例如,我的 app.py:

from flask import Flask, render_templateapp = Flask(__name__)@app.route("/index")定义索引():a=3b=4c=a+breturn render_template('index.html',c=c)@app.route("/dif")定义差异():d=c+areturn render_template('dif.html',d=d)如果 __name__ == "__main__":应用程序运行()

在路由/dif下,变量d是通过取已经计算好的c和a的值来计算的.如何在页面之间共享变量c和a,使变量d被计算并渲染到dif.html?

谢谢

解决方案

如果你不想使用 错误显示当processes=10data.adata.c的值仍然是None.><小时>

所以,证明我们不应该在网络应用程序中使用全局变量.

我们可能会使用

I am learning Flask and have a question regarding use of variables in the context of routes.For Example, my app.py:

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/index")
def index():

   a=3
   b=4
   c=a+b

return render_template('index.html',c=c)

@app.route("/dif")
def dif():

   d=c+a

   return render_template('dif.html',d=d)


if __name__ == "__main__":
   app.run()

Under the route /dif the variable d is calculated by taking the values of already calculated c and a.How to share variables c and a between pages, so that variable d is calculated and rendered to dif.html?

Thank You

解决方案

If you do not want to use Sessions one way to store data across routes is (See the update below):

from flask import Flask, render_template
app = Flask(__name__)

class DataStore():
    a = None
    c = None

data = DataStore()

@app.route("/index")
def index():
    a=3
    b=4
    c=a+b
    data.a=a
    data.c=c
    return render_template("index.html",c=c)

@app.route("/dif")
def dif():
    d=data.c+data.a
    return render_template("dif.html",d=d)

if __name__ == "__main__":
    app.run(debug=True)

N.B.: It requires to visit /index before visiting /dif.


Update

Based on the davidism's comment the above code is not production friendly because it is not thread safe. I have tested the code with processes=10 and got the following error in /dif:

The error shows that value of data.a and data.c remains None when processes=10.


So, it proves that we should not use global variables in web applications.

We may use Sessions or Database instead of global variables.

In this simple scenario we can use sessions to achieve our desired outcome. Updated code using sessions:

from flask import Flask, render_template, session
app = Flask(__name__)
# secret key is needed for session
app.secret_key = 'dljsaklqk24e21cjn!Ew@@dsa5'
@app.route("/index")
def index():
    a=3
    b=4
    c=a+b
    session["a"]=a
    session["c"]=c
    return render_template("home.html",c=c)

@app.route("/dif")
def dif():
    d=session.get("a",None)+session.get("c",None)
    return render_template("second.html",d=d)

if __name__ == "__main__":
    app.run(processes=10,debug=True)

Output:

这篇关于跨 Flask 路由使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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