python - 如何将 Flask 中的数据发送到另一个页面?

标签 python flask

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

@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 功能。这个目的的术语是什么..?

最佳答案

get 请求可以从一个路由到另一个路由传递数据。

您几乎可以在 booking route 获取提交的 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>

输出:

Home route with a form to submit date

home route

获取预订 route 的日期

getting the date in booking route

缺点:

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

备选方案:

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

关于python - 如何将 Flask 中的数据发送到另一个页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55447599/

相关文章:

python - 如何在使用 tkinter 工具栏缩放时更改绘图的宽度

python - 我应该使用 Python casefold 吗?

javascript - 获取网页中arduino数字引脚的状态

python - Flask-Babel 多语言 URL 路由

python - 具有字符串/分类特征(变量)的线性回归分析?

python - pytest - 如何使其递归搜索?

python - PyDev 不识别导入

python - Werkzeug 引发 BrokenFilesystemWarning

Python Flask SocketIO 在@socketio 上下文之外广播

python - 如何将 angular2 与 jinja2 模板和 flask 结合起来