我试图以表格形式输入值并从数据库中获取值,但我无法做到这一点。我正在使用名为travel的mysql数据库,并将表也命名为travel。我在下面附加了我的python代码和模板 我的错误是:werkzeug.exceptions.BadRequestKeyError werkzeug.exceptions.HTTPException.wrap..newcls:400错误的请求:KeyError:'stay'
Python代码:
from flask import Flask, render_template, request, redirect,flash,url_for,session
from flask_mysqldb import MySQL
import datetime
import time
app = Flask(__name__)
app.config['MYSQL_HOST'] = "127.1.1.0"
app.config['MYSQL_USER'] = "root"
app.config['MYSQL_PASSWORD'] = "****"
app.config['MYSQL_DB'] ="travel"
app.secret_key="gsabo"
mysql = MySQL(app)
@app.route('/')
@app.route('/questions',methods=['GET', 'POST'])
def questions():
if request.method == "POST" or "GET":
userDetails= request.form
cur = mysql.connection.cursor()
stay=userDetails['stay']
Budget=userDetails['Budget']
print(Passengers,Weather,Transport,stay,Interests)
cur.execute("select * from travel where stay=%s,Budget=%s",(stay,Budget,))
mysql.connection.commit()
userDetails=cur.fetchone()
Location=userDetails[3]
Budget=userDetails[4]
return render_template('questions.html',Budget=Budget,Location=Location)
return render_template('questions.html')
if __name__ == '__main__':
app.run(debug=True)
HTML模板:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Travel</title>
</head>
<body>
<div id="content">
<form action="/questions" method="post">
<table>
<tr><th colspan="2">Find Travel Detination and Budget</th></tr>
<tr>
<td> stay<font color='red'>*</font> :</td>
<td><select name="stay">
<option>Select</option>
<option value="Hotel">Hotel</option>
<option value="Tent">Tent</option>
</select></td>
</tr>
<tr>
<td>Budget<font color='red'>*</font> :</td>
<td><select name="Budget">
<option>Select</option>
<option value="1000">1000$</option>
<option value="2000">2000$</option>
<option value="3000">3000$</option>
<option value="4000">4000$</option>
<option value="5000">5000$</option>
<option value="6000">6000$</option>
<option value="7000">7000$</option>
<option value="8000">8000$</option>
<option value="9000">9000$</option>
<option value="10000">10000$</option>
</select></td>
</tr>
<td><input type="submit" value="Submit" href="hello" /></td>
<td><input type="reset" value="Reset" /></td>
</tr>
<tr>
<td>Budget:</td>
<td><input type="number" name="Budget" value="<%=Budget %>" readonly disabled/></td>
</tr>
<tr>
<td>Location:</td>
<td><input type="text" name="Location" value="<%=Location %>" readonly disabled/></td>
</tr>
</form>
</table>
</div>
</body>
</html>
答案 0 :(得分:0)
<td><select name="stay">
<option>Select</option>
<option value="Hotel">Hotel</option>
<option value="Tent">Tent</option>
</select></td>
您具有此代码块,大概可以使用value = "Hotel"
或value = "Tent"
到/ questions,但在代码中仅占value = "stay"
。您需要考虑所有情况