I'm trying to create a flask app where I have a text box on the webpage. When submit is pressed it searches what was entered into the text box in a postgres datbase table.
I'm getting the following error:
Bad Request The browser (or proxy) sent a request that this server could not understand."
My code is as follows:
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)
and my html file:
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>
I'm sure it's something real easy and simple that will fix it, but i'm struggling so any help would be hugely appreciated.
Since your
homepagefunction receives both GET and POST requests you need to handle each case separately. You don't haverequest.formwhen you recieve GET request.Please be aware that it's dangerous to put user's input directly into your SQL query without sanitizing it as it opens your app to SQL injection attacks.