0

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

2

Since your homepage function receives both GET and POST requests you need to handle each case separately. You don't have request.form when you recieve GET request.

@app.route('/', methods=['GET', 'POST'])
def homepage():
    if request.method == 'POST'
        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)
    else:
        return render_template('main.html')

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.

Denis Fetinin
  • 1,746
  • 1
  • 9
  • 15
  • Thanks for your answer, it worked! However I'm getting this error now when I enter anything into my text box and press enter: TypeError: 'dict' object does not support indexing –  Jul 05 '18 at 11:24
  • I guess it is related to [this](https://stackoverflow.com/questions/8657508/strange-sqlalchemy-error-message-typeerror-dict-object-does-not-support-inde). If that won't help I'd recommend you to raise a new question. @keyring88 – Denis Fetinin Jul 05 '18 at 11:41