Search code examples
pythonflasksqlalchemypsycopg

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.


Solution

  • Maybe you should use the sqlalchemy to execute rp = db.session.execute("select * from test") result_set = rp.fetchall()