跨Flask路线使用变量

2024-05-17 02:53:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在route/dif下,变量d是通过取已计算的c和a的值来计算的。如何在页面之间共享变量c和a,从而计算变量d并将其呈现为dif.html?

谢谢你


Tags: namefrompyappflask路由indexreturn
2条回答

如果不想使用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)

注意:在访问/dif之前需要访问/index


更新

根据davisim的评论,上面的代码不适合生产,因为它不是线程安全的。我用processes=10测试了代码,在/dif中得到了以下错误:

internal server error for processes=10 该错误表明data.adata.c的值在processes=10时仍保持None


因此,它证明了我们不应该在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)

输出:

indexdif

您可以在flask中使用变量,方法是在URL中写入这样从HTML传递的变量。 我是说

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"

作为参考:

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

相关问题 更多 >