I'm new to SQLAlchemy and PostgreSql, so apologies for the newbie question. I'm trying to connect to a table in a remote PostgreSql server using flask-alchemy, and read all the table records. It doesn't have to be flask-sqlalchemy specifically, but I do need to read the table records.
The table has 3 records, but it always comes back as zero records when I step through the code.
I'm using python 3.7, visual studio code with an virtual environment in windows 10.
I checked several articles already:
https://flask-sqlalchemy.palletsprojects.com/en/2.x/#
https://stackabuse.com/using-sqlalchemy-with-flask-and-postgresql/
https://realpython.com/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/
https://www.askpython.com/python-modules/flask/flask-postgresql
Here's my app.py code:
import sys, os
from flask import Flask, request, jsonify, make_response, session
# SQL ALCHEMY imports
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://userid:password@server:1234/db_name'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
class DummyTable(db.Model):
field_id = db.Column(db.Integer, primary_key=True)
desc = db.Column(db.String(10), nullable=False)
def __repr__(self):
return '<Desc %r>' % self.desc
@app.route('/test', methods=["GET"])
def get_records():
from app import DummyTable
db.create_all()
dummy_table = DummyTable.query.all()
results = [
{
"field_id": dummy_table.field_id,
"desc": dummy_table.desc
} for record in dummy_table]
return {"results": results}
if __name__ == "__main__":
app.run()
Any help is really appreciated. Thanks.
I believe you're missing a
db.session.commit()
After db.create_all()
I ended up using psycopg2 instead
import psycopg2
conn = psycopg2.connect(dbname="blah", user="blah", password="blah", host="some-machine", port="9999")
cur = conn.cursor()
cur.execute("SELECT * FROM private_schema.mytable;")
items = cur.fetchall()
for row in items:
print("pkey = ", row[0], )
print("val = ", row[1], "\n")
cur.close()
conn.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.