如何使用flask和sqlalchemy进行选择查询?

时间:2017-02-14 11:35:36

标签: python postgresql flask flask-sqlalchemy

我是使用flask和SQLAlchemy的新手,我在postgress中有一个数据库,这个数据库有table" data" 200条记录,我想做一个Select语句,但是当我这样做时总是给我同样的错误,这是我的代码:

这是我的model.py

wsimport

这是我的烧瓶应用程序:

from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Data(Base):
    __tablename__ = 'data'
    ids = Column(Integer(), primary_key=True)
    customer_id = Column(String())
    inventory_id = Column(String())
    device_id = Column(String())

    def toJSON(self):       
        json = {
            "ids":self.ids,
            "customer_id":self.customer_id,
            "inventory_id":self.inventory_id,
            "device_id":self.device_id,     
        }

        return json

这不起作用,并且总是有相同的错误:

  

AttributeError:type object' Base'没有属性   ' psirt_alerts_view'

如何选择?

更新:

from flask_sqlalchemy import SQLAlchemy
from flask import Flask, render_template, request
from flask_cors import CORS, cross_origin
from model import Data, Base

app = Flask(__name__)
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost/mydatabase'
db = SQLAlchemy(app)
data = []

def index():
    test_data()
    return render_template("index.html",result = data)

def test_data():
    sss = Base.Data.query.filter_by(ids=5).first()
    print sss

app.add_url_rule('/', 'index', index)

if __name__ == '__main__':
    app.run(debug = True, threaded=True)

1 个答案:

答案 0 :(得分:3)

Col001 = S.[Col001]实例具有会话对象,因此您可以执行以下查询:

db