python的flask框架下不同路由之間傳遞變量的一種辦法


我查了一下解決這個問題的辦法,一般是設定全局變量,今天介紹一種新辦法

上代碼difrouters.py

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)

index.html

<html>
<head>
  <title>Home</title>
</head>
<body>
  結果c={{ c }}
</body>
</html>

dif.html

<html>
<head>
  <title>different router</title>
</head>
<body>
  結果d={{ d }}
</body>
</html>

運行結果

在路由index上的結果

 

 在路由dif上的結果

 

 代碼見https://github.com/qingnvsue/flask 中的difrouters文件夾


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM