Jinja Flask Templating SQLAlchemy Displaying Multiple Results - python

I'm trying to create a simple search tool that searches an existing Postgres table, using Flask, Jinja & SQLAlchemy.
It's all working, except when I search, the result that is displayed on my page is like this:
Note the bit i've circled, is what would be displayed if I did the same search just using Postgres/pgadmin. It's returning multiple random results.
Below is what would return by using Pgadmin:
Any ideas? My code is below.
App.py
from flask import Flask, render_template, request
from sqlalchemy import create_engine
from sqlalchemy import text
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='xxx://xxx:xxx#xxx:xxx/xxx'
engine = create_engine('postgresql+psycopg2://xxx:xxx#xxxr:xxx/xxx')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db=SQLAlchemy(app)
#app.route('/', methods=['GET', 'POST'])
def homepage():
if request.method == 'POST':
jn = request.form['jobnumber']
rp = db.session.execute(text("SELECT cost FROM public.options where cast(optionno AS VARCHAR) like :jn"), {"jn": f"%{jn}%"})
result_set = rp.fetchall()
return render_template('main.html', result_set=result_set, jn=jn)
else:
return render_template('main.html')
if __name__ == "__main__":
app.run(debug=True)
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" id="jobnumber">
<input name="jobnumber" type="text" placeholder="jobnumber">
</form>
<table>
<td>
<h1> Results</h1>
<p>{{result_set}}</p>
</td>
</table>
</body>
</html>
How do I get it to only display the same as what PGAdmin would display?

You seem to be searching with %s in flask & without them in pgAdmin. If you need the same result in both, use the same query.
Enclosing the search string with % indicates to the SQL engine that you want to have values that contain your search string. Not just an exact match.

Related

Prepopulating a textarea element with Flask

I am trying to write a program that reads a file and outputs it to the textarea. The user can then edit the file and then click the submit button in order to submit the changes.
Currently, I have a method of obtaining the user's input (request.form), however I do not know how to prepopulate the text area element.
Flask
from flask import Flask
from flask import render_template
from flask import request
app = Flask(__name__)
#app.route('/')
def hello():
return render_template("index.html")
#app.route('/', methods=['POST'])
def submit():
return 'You entered: {}'.format(request.form['whitelist'])
if __name__ == '__main__':
app.run(host="localhost", port=8000, debug=True)
HTML
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Index</title>
</head>
<body>
<h1 style="color: blue">Index</h1>
<p>This is an HTML file served up by Flask</p>
<p>Whitelist:</p>
<form action="{{ url_for('submit') }}" method="post">
<textarea id="whitelist" name="whitelist" rows="4" cols="50"></textarea>
<input type="submit">
</form>
</body>
</html>
So is their a method that exists such that one can prepopulate the textarea?
Example
my_file_data = read_my_file(file)
Flask.output(element_id = "whitelist", input = my_file_data)
Implementing Solution
Try the following changes in your code (i assume that your file is a .txt but it can work with other file types with some changes):
Flask
#app.route('/')
def hello():
with open('your_file') as f:
t=f.read()
return render_template("index.html", t=t)
HTML
<textarea id="whitelist" name="whitelist" rows="4" cols="50"> {{t}} </textarea>

SQLAlchemy Engine Result Proxy error (Flask Python)

I'm creating a search tool, that uses psycopg, flask and SQLAlchemy to return results from a Postgres database.
I'm getting the error:
sqlalchemy.engine.result.ResultProxy object at....
This is happening when I am searching for the 'job number'.
I'm led to believe that this is due to not interfacing with the ResultProxy, but I cannot figure out where it is wrong?
app.py
from flask import Flask, render_template, request
from sqlalchemy import create_engine
from sqlalchemy import text
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://xx:xx#rx:x/xxx'
engine = create_engine('postgresql+psycopg2://xx:xxx#rx:x/x')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db=SQLAlchemy(app)
#app.route('/', methods=['GET', 'POST'])
def homepage():
if request.method == 'POST':
jn = request.form['jobnumber']
result_set = engine.execute(text("SELECT cost FROM public.options where cast(optionno AS VARCHAR) LIKE :jn"), {"jn": f"%{jn}%"})
result_set.close()
return render_template('main.html', result_set=result_set, jn=jn)
else:
return render_template('main.html')
if __name__ == "__main__":
app.run(debug=True)
Main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>xx</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>x</p>
<form method="POST" id="jobnumber">
<input name="jobnumber" type="textbox" placeholder="jobnumber">
</form>
<table>
<td>
{{result_set}}
</td>
</table>
</body>
</html>
Any help would be greatly appreciated.
Maybe you should use the sqlalchemy to execute
rp = db.session.execute("select * from test")
result_set = rp.fetchall()

Bad Request - The browser (or proxy) sent a request that this server could not understand [duplicate]

This question already has an answer here:
Flask view shows 400 error instead of template with form
(1 answer)
Closed 4 years ago.
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 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.

Why am I getting a 500 error with this code?

I am trying to create a site with a webform using Flask, but I keep getting a 500 error
Here is my template/main.html
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample Page</title>
<meta name="viewport" content="width=device-width"
initial=scale=1/>
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='favicon.ico') }}" rel="shortcut icon">
</head>
<h2>Hello, this site is meant to test my fill_web_form.py script</h2>
<br>
<br>
<h1>Test Form</h1>
<form action="/" method="post" name="login">
{{ render_field(form.test_form) }}<br>
<p><input type="submit" value="Sign In"></p>
</form>
</html>
Here is my init.py file
from flask import Flask, render_template
#import sqlite3
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("main.html")
if __name__ == "__main__":
app.run()
Here is my form.py file
from flask.ext.wtf import Form
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired
class LoginForm(Form):
test_form = StringField('test_form', validators=[DataRequired()])
Why do I keep getting a 500 error? I cant figure it out.
Run in debug mode app.run(debug=True) to see more information in browser.
You should import form and send to template. You may need secret_key to use csrf. etc.
from form import LoginForm
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
#app.route('/')
def homepage():
return render_template("main.html", form=LoginForm())

Why am I getting a 500 error when trying to connecto to an sqlite database?

I trying to make a site that passes data from a web form to an sqlite database. I keep getting a 500 error. When I type the ip address and get to main.html, it displays the page with no errors, but when I submit the form I get a 500 error.
It doesn't give me the stacktrace is just says The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
It's hard to debug this because when I access the server through a browser, it doesn't give me details about the error. And when I run flask run in putty, it doesn't give me an error, it just gives me this
searching http://127.0.0.1 in my browser doesn't work, I'm guessing because flask run is running on the server and not on my computer.
Here is my code:
__init__.py
from flask import Flask, render_template
from forms import TestForm
import sqlite3
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("main.html", form=TestForm())
#app.route('/post', methods=['POST'])
def post():
conn = sqlite3.connect("sample.db")//If I remove these two lines
conn.close() //The code works without error
return render_template("test.html")
if __name__ == "__main__":
app.run(debug=True)
forms.py
from flask_wtf import Form
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired
class TestForm(Form):
test_form = StringField('test_form', validators=[DataRequired()])
main.html
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample Page</title>
<meta name="viewport" content="width=device-width"
initial=scale=1/>
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='favicon.ico') }}" rel="shortcut icon">
</head>
<h2>Hello, this site is meant to test my fill_web_form.py script</h2>
<br>
<br>
<h1>Test Form</h1>
<form action="/post" method="post" name="test">
{{ form.test_form(size=80) }}
<p>Form</p><br>
<p><input type="submit" value="Test Form"></p>
</form>
</html>
test.html
<DOCTYPE html>
</html>
<head>
<title>test</title>
</head>
<body>
<h1>Testing 123</h1>
</body>
</html>

Categories

Resources