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.
Jean-Vicente De Carvalho :
I believe you're missing a\ndb.session.commit()\n\nAfter db.create_all()",
2021-04-07T02:27:09