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
从一条路由到另一条路由的请求可以传递数据。
您几乎可以在路由中获取提交的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)
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 来促进多部分表单。
推荐阅读
- git - 将 VSCode 设置为我的 Mac M1 的 Git 默认编辑器
- html - 浏览器如何知道在页面上打开文件时要读取什么
- regex - 正则表达式在两个关键字(从和到)之后获取字符串
- laravel - 如何确定我的 laravel 收藏是否匹配
- window - SQLiteStudio 中的 Lag() 函数
- javascript - Highcharts 网络图布局
- python - Python打印整数字符串混合和组匹配问题
- linux - 如何结束对特定输出的期望交互?
- python - 在 VS CODE 中设置 cwd
- c# - Unity C#如何避免点击并仅通过滑动来按字符移动