我正在尝试创建一个flask应用程序,其中我在网页上有一个文本框。当按下submit时,它将搜索在postgres datbase表的文本框中输入的内容。
我得到以下错误:
Bad Request The browser (or proxy) sent a request that this server could not understand."
我的代码如下:
app.py
from flask import Flask, render_template, request
from sqlalchemy import create_engine
app = Flask(__name__)
app.config['DEBUG']
db_string = "postgres://xx:xx@xx:5432/xx"
db = create_engine(db_string)
@app.route('/', methods=['GET', 'POST'])
def homepage():
jn = request.form['jobnumber']
result_set = db.execute("SELECT cost FROM public.options where optionno = (f'%{jn}%')").fetchall()
return render_template('main.html', test=result_set, jn=jn)
if __name__ == "__main__":
app.run(debug=True)
以及我的html文件:
main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>xxx</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
<p>xxx</p>
<form method="POST">
<input name="jobnumber" type="submit" placeholder="jn">
</form>
<table>
<td>
{{test}}
</td>
</table>
</body>
</html>
我相信这是一件非常简单容易的事情,但我正在努力,所以任何帮助都会非常感谢。
由于
homepage
函数同时接收GET和POST请求,因此需要分别处理每个案例。当您收到GET请求时,您没有request.form
。请注意,将用户的输入直接放入您的SQL查询中而不进行清理是危险的,因为它会打开您的应用程序,从而受到SQL injection攻击。
相关问题 更多 >
编程相关推荐