在Flask路线上使用变量

时间:2018-04-05 04:07:01

标签: python flask routes jinja2

我正在学习Flask并且在路由的上下文中有关于变量使用的问题。例如,我的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()

在路径/ dif之下,通过获取已计算的c和a的值来计算变量d。如何在页面之间共享变量c和a,以便计算变量d并将其渲染为dif.html?

谢谢

2 个答案:

答案 0 :(得分:4)

如果您不想使用Sessions单一方式在路线上存储数据请参阅下面的更新):

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。:访问/index之前需要访问/dif

更新

根据davidism的评论,上面的代码不是生产友好的,因为它不是线程安全的。我已使用processes=10对代码进行了测试,并在/dif中收到了以下错误:

internal server error for processes=10 该错误表明data.adata.cNone的值仍为processes=10

因此,它证明我们不应该在Web应用程序中使用全局变量

我们可能会使用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)

输出:

index dif

答案 1 :(得分:0)

您可以通过在URL中编写从HTML传递的变量来使用flask中的变量。 ,

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("<variable1>/dif/<variable2>")
    def dif(variable1,variable2):

       d=c+a

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


    if __name__ == "__main__":

你的HTML会是这样的: 形式:

<form action="/{{ variable1 }}/index/{{ variable2}}" accept-charset="utf-8" class="simform" method="POST"

as href:

<a href="{{ url_for('index',variable1="variable1",variable2="variable2") }}"><span></span> link</a></li>