简体   繁体   中英

How to read data from postgresql in python using Flask and SQLAlchemy?

I started creating a flask application as I will be needing to do some visualization of some data that was recently transferred to a local postgresql database.

I have a lot of tables (33) which all have the same kind of content as currently just works as containers for different types of data (They contain a JSON object that's different in each of the tables though).

The tables are named "Table_#" (where # symbolizes a number among a defined subset of numbers).

models.py

I have created the following model:

from sqlalchemy import BigInteger, Column, JSON, Text
from app import db

class Table_1(db.Model):
    __tablename__ = 'table_1'

    id = db.Column(BigInteger, primary_key=True)
    did = db.Column(Text)
    timestamp = db.Column(BigInteger)
    data = db.Column(JSON)
    db_timestamp = db.Column(BigInteger)

    def __repr__(self):
        return '<1_Data %r>' % (self.did)

to test if I can actually grab some data from my postgresql.

__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)

from app import views, models

config.py

In my config.py I have the following:

SQLALCHEMY_DATABASE_URI = "postgresql://<username>:<password>@localhost:5432/backupdata" //Ofc <username> and <password> isn't my credentials..

In my terminal (Windows cmd) I've tried running the following:

>python
>>>from app import db, models
>>>row = models.Table_1.query.get(1)

But for some reason when I try to print my row nothing is output.

I was hoping someone could have an idea why that is?

I updated my model a bit, to see that I actually got a specific row.

from sqlalchemy import BigInteger, Column, JSON, Text
from app import db

class Table_1(db.Model):
    __tablename__ = 'table_1'

    id = db.Column(BigInteger, primary_key=True)
    did = db.Column(Text)
    timestamp = db.Column(BigInteger)
    data = db.Column(JSON)
    db_timestamp = db.Column(BigInteger)

    def __repr__(self):
        return '<1_Data %r, %r>' % (self.did, self.id)

And then the following query made me aware that actually have a working connection to SQLAlchemy through my flask application.

row = models.Table_910.query.filter_by(did='357139052424715').first()

Knowing that I have one item with the above did I could get a single item:

<1_Data '357139052424715', 738390911>

As stated in your answer, you would need to use the firts() method. Another option would be to limit your query as follows:

Table.query.limit(1).all()

This way you don't need a filter and can just retrieve the first item in the query (which seems to be what you wanted to do originally with query.get(1)

See here for more info.

This sloution is with postgres and Flask without SQLAlchemy

@app.route('/contextget', methods=['GET']) 
def contextget():
    sql_query ="""SELECT * FROM context"""
    out = cur.execute(sql_query)
    context_records = cur.fetchall() 
    ContextRootKeys = []
    outp ="Print each row and it's columns values"
    for row in context_records:
        ContextRootKeys.append(row[1])
    conn.commit()
    print(ContextRootKeys)
    return outp

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM