我正在使用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')
Run Code Online (Sandbox Code Playgroud)
这 date变量是来自表单的请求,现在我想将date数据发送到booking函数。什么是这个目的的术语..?
get从一条路由到另一条路由的请求可以传递数据。
您几乎可以date在booking路由中获取提交的值。
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)
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
main/booking.html:
<html>
<head></head>
<body>
<h3>Booking page</h3>
<p>
Seleted date: {{ date }}
</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
输出:
回家路线用表格提交日期
获取预订路线中的日期
缺点:
date:)作为 URL 参数从一个路由传递到另一个路由。booking路由)。备择方案:
| 归档时间: |
|
| 查看次数: |
10114 次 |
| 最近记录: |