Flask:如何在html页面app路由之间传递变量

时间:2016-09-14 14:54:07

标签: python html flask

我有一个getvlanconfig.html页面,其中包含一个收集vlanid和vlannetwork等信息的表单。我希望能够将该信息传递给在提交表单时加载的页面showvlanconfig.html。 我是Flask的新手,无论我做什么查找,我都无法找到最好的方法。我也看过会议,我不确定这是否是我的选择。

    from flask import Flask, render_template, url_for, flash, request, redirect


    app = Flask(__name__)

    @app.route('/')
    def homepage():
      return render_template("index.html")

    @app.route('/getvlanconfig/', methods=["GET","POST"])
    def getvlan():

      try:

          if request.method == "POST":
             getvlanid = request.form['vlanid']
             getvlannetwork = request.form['vlannetwork']

             return redirect(url_for('showvlan'))
      except Exception as e:

             return render_template("vlanconfig.html")


 @app.route('/showvlanconfig', methods=["GET","POST"])
 def showvlan():
      try:          
         getvlanid = ???
         getvlannetwork = ?? 
         return render_template("index.html", vlanid = getvlanid, vlannetwork = getvlannetwork)
      except Exception as e:
         flash(e)


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

1 个答案:

答案 0 :(得分:1)

使用会话在来自同一客户端的请求之间存储数据。

from flask import session

def getvlan():
    session['vlanid'] = request.form['vlanid']
    return redirect(url_for('showvlan'))

def showvlan():
    vlanid = session['vlanid']
    ...

使用数据库(或其他外部持久存储)以更普遍的方式存储数据。