【问题标题】:How to send data in Flask to another page?如何将 Flask 中的数据发送到另一个页面?
【发布时间】:2021-08-25 15:09:52
【问题描述】:

我正在使用 Flask 制作订票应用。但是现在我对如何将数据从一个页面发送到另一个页面有点困惑,就像这个 sn-p 的代码:

@app.route('/index', methods = ['GET', 'POST'])
def index():
    if request.method == 'GET':
        date = request.form['date']
        return redirect(url_for('main.booking', date=date))
    return render_template('main/index.html')


@app.route('/booking')
def booking():
    return render_template('main/booking.html')

date 变量是来自表单的请求,现在我想将 date 数据发送到 booking 函数。什么是用于此目的的术语..?

【问题讨论】:

  • 您尝试过会话存储吗?重定向方法不允许将数据发送到另一个页面。
  • 我现在正在阅读它@VillageMonkey,但仍在考虑,在这种情况下我应该使用会话还是cookie..?

标签: python flask


【解决方案1】:

get 请求可以从一条路由传递到另一条路由。

您几乎可以在booking 路由中获取提交的date 值。

app.py:

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

app = Flask(__name__)

@app.route('/', methods = ['GET', 'POST'])
def index():
    if request.method == 'POST':
        date = request.form.get('date')
        return redirect(url_for('booking', date=date))
    return render_template('main/index.html')


@app.route('/booking')
def booking():
    date = request.args.get('date', None)
    return render_template('main/booking.html', date=date)    

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

main/index.html:

<html>
  <head></head>
  <body>
    <h3>Home page</h3>
    <form action="/" method="post">
      <label for="date">Date: </label>
      <input type="date" id="date" name="date">
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

main/booking.html:

<html>
  <head></head>
  <body>
    <h3>Booking page</h3>
    <p>
      Seleted date: {{ date }}
    </p>
  </body>
</html>

输出:

带有提交日期的表格的首页路线

获取预订路线中的日期

缺点:

  • 值(例如:date)作为 URL 参数从一个路由传递到另一个路由。
  • 任何有获取请求的人都可以访问第二部分(例如booking 路由)。

替代方案:

  • 按照@VillageMonkey 的建议使用会话存储。
  • 使用 Ajax 简化多部分表单。

【讨论】:

  • 为什么如果将值作为 URL 参数传递,包括缺点?
  • 这取决于数据。如果数据包含敏感信息(例如:密码),则不应通过 URL 参数发送。
  • 这种方式在这种情况下是否安全..?,或者像我的问题一样发送数据的最佳做法是什么..?,或者我应该使用会话..?
  • 如果你没有通过 URL 参数传递任何敏感值,你可以使用它。否则,请尝试会话存储。
  • 非常感谢@arsho 的最佳解释,我从你那里学到了很多知识。
【解决方案2】:

您还可以使用烧瓶会话将数据从一个页面发送到另一个页面。

 from flask import Flask, render_template, request, jsonify, url_for, redirect, 
 session

 app = Flask(__name__)

 @app.route('/', methods = ['GET', 'POST'])
 def index():
    if request.method == 'POST':
        date = request.form.get('date')
        session["date"] = date
        return redirect(url_for('booking', date=date))
    return render_template('main/index.html')


 @app.route('/booking')
 def booking():
    date = session.get("date")
    return render_template('main/booking.html', date=date)    

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

【讨论】:

    猜你喜欢
    • 2023-02-06
    • 2021-04-15
    • 2021-08-21
    • 2020-11-12
    • 2020-08-16
    • 2014-05-15
    • 1970-01-01
    • 2013-01-24
    • 2014-01-12
    相关资源
    最近更新 更多