您当前的位置: 首页 >  flask

IT之一小佬

暂无认证

  • 1浏览

    0关注

    1192博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

flask框架不同路由之间传递变量

IT之一小佬 发布时间:2022-04-25 00:16:55 ,浏览量:1

本文总结了两种方法:全局变量和类方法

1、全局变量

示例代码:

from flask import Flask, render_template

app = Flask(__name__)

ret = []


@app.route("/index")
def index():
    s = "I love you!"
    t = "Me Too!"
    global ret
    ret.append(s)
    ret.append(t)
    return render_template("index.html", m=ret)


@app.route("/index2")
def index2():
    global ret
    return render_template("index2.html", n=ret)


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

index.html




    
    
    flask框架


    {{ m }}

index2.html




    
    
    flask框架2


    {{ n }}

运行效果:

 

2、类方法

示例代码:

from flask import Flask, render_template

app = Flask(__name__)


class DataBase(object):
    x = None
    y = None
    z = None


data = DataBase()


@app.route("/index")
def index():
    s = "I love you!"
    t = "Me Too!"
    m = s + t
    data.x = s * 3
    data.y = t * 2
    return render_template("index.html", m=m)


@app.route("/index2")
def index2():
    n = data.x + data.y
    return render_template("index2.html", n=n)


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

index.html




    
    
    flask框架


    {{ m }}

index2.html




    
    
    flask框架2


    {{ n }}

运行效果:

 

注意事项:

步骤1.创建一个名为“ templates”的新文件夹

步骤2.将“ index.html”移动到“ templates”文件夹中

步骤3.在索引函数中,返回render_template('index.html',m = m)

关注
打赏
1665675218
查看更多评论
立即登录/注册

微信扫码登录

0.1570s