我希望获得"名称"和"尺寸"用户键入搜索框的值。
但显而易见的问题是,我试图从method: "POST"
hmtl表单获取值。
我的html操作只引用了{{ url_for('main') }}
html,而不想在{{url_for(' search')}} html中检索这些值。
以下是模板:
import sqlite3
from flask import Flask,render_template, url_for, redirect, request
app = Flask(__name__)
conn = sqlite3.connect('shoes.db', check_same_thread=False)
c = conn.cursor()
@app.route("/", methods=["GET", "POST"])
def main():
if request.method == 'GET':
return render_template('main.html')
elif request.method == 'POST':
name = request.form.get('name')
size = request.form.get('size')
return redirect(url_for('search'))
@app.route("/search/", methods=["GET", "POST"])
def search():
# Need to get the 'name' and 'search' values from input, so this way is incorrect.
name = request.args.get("name")
size = request.args.get("size")
c.execute("SELECT * FROM shoes WHERE name LIKE ? AND sizes LIKE ? ORDER BY price",
('%'+name+'%','%'+size+'%'))
p = c.fetchall()
url = [p[i][0] for i in range(len(p))]
names = [p[i][1] for i in range(len(p))]
prices = [p[i][2] for i in range(len(p))]
sizes = [p[i][3] for i in range(len(p))]
shoe_type = [p[i][4] for i in range(len(p))]
return render_template('search.html' , url=url, names=names, prices=prices,
sizes=sizes, shoe_type=shoe_type)
if __name__ == '__main__':
app.run(debug=True)
main.html中:
{% extends "layout.html" %}
{% block content %}
<form action = "{{ url_for('main') }}" class="form" method = "POST" >
<h1>Soccer Shoes Finder</h1>
<div class="line-separator"></div>
<div class="container-fluid">
<input name = "name" type="text" placeholder="Name"/>
<input name = "size" type="text" placeholder="Size"/>
<button class="glyphicon glyphicon-search" aria-hidden="true"></button>
</div>
</form>
{% endblock %}
search.html:
{% extends "layout.html" %}
{% block content %}
<div class= "container">
<h2>Results:</h2>
<table class="table table-striped">
<thead>
<tr>
<th>url</th>
<th>Name</th>
<th>Prices</th>
<th>Sizes</th>
<th>Shoe Type</th>
</tr>
</thead>
<tbody>
{% for i in range(url|length) %}
<tr>
<td><a href={{url[i]}}>aa</td>
<td>{{names[i]}}</td>
<td>${{prices[i]}}</td>
<td>{{sizes[i]}}</td>
<td>{{shoe_type[i]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
任何人都知道如何实现这一目标?希望我所说的是有道理的。感谢。
答案 0 :(得分:2)
简化您的主要路线,似乎没有理由在此处发布数据:
@app.route("/")
def main():
return render_template('main.html')
通过在 main.html Jinja模板中更改此行, POST
将数据直接发送到搜索端点:
<form action="{{ url_for('search') }}" class="form" method="POST">
由于此页面呈现取决于具有表单数据,我只是将其设置为仅接受POST方法,但这取决于您。您需要使用request.form (或request.values,如果您还想支持查询字符串GET
方法)来访问此处的值。
@app.route("/search/", methods=["POST"])
def search():
name = request.form.get("name")
size = request.form.get("size")
假设您的数据库代码正常工作,其余部分应按预期工作