使用Flask SQL Alchemy

时间:2016-08-11 20:39:04

标签: python flask sqlalchemy

from flask import Flask
import requests
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/localDB'


class MainResult(db.Model):
    __tablename__ = "mainresult"

    metadata_key = db.Column(db.String(128), primary_key=True)
    individualResults = db.relationship('IndividualResult', backref='mainresult', lazy='dynamic',
                                        cascade="all, delete-orphan")

    def __init__(self, metadata_key):
        self.metadata_key = metadata_key

class IndividualResult(db.Model):
    __tablename__ = "individualresult"

    metadata_key = db.Column(db.String(128), db.ForeignKey('mainresult.metadata_key'), primary_key=True)
    ts = db.Column(db.String(50), primary_key=True)

    def __init__(self, metadata_key, ts):
        self.metadata_key = metadata_key
        self.ts = ts




@app.route('/')
def hello_world():
    # This throws an error.
    print IndividualResult.query.get("03d49625b00643058a40eb8672e94f4e")
    # Error too
    IndividualResult.query.filter_by(metadata_key='03d49625b00643058a40eb8672e94f4e').first()

    # This works.
    print MainResult.query.get("03d49625b00643058a40eb8672e94f4e")

    return 'Hello World!'

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

我有上面的代码,正确插入了数据。我可以使用MainResult.query查询,但我无法使用IndividualResult.query进行查询。

返回的错误是

属性错误:没有' InstrumentedAttribute'对象也不是'比较器'与IndividualResult.query相关联的对象具有属性' get'

它非常奇特,因为它们几乎相同

完整Stacktrace:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/Park/PycharmProjects/Flask_24Aug/Main_Flask.py", line 170, in hello_world()
    print IndividualResult.query.get("03d49625b00643058a40eb8672e94f4e","1470860955")
  File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 193, in __getattr__
    key)
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with IndividualResult.query has an attribute 'get'

1 个答案:

答案 0 :(得分:0)

当您使用get时,您需要为其指定主键,如果您IndividualResult已经定义了复合主键(由多列组成的主键),那么要查询您需要指定这两列:

print(IndividualResult.query.get(("03d49625b00643058a40eb8672e94f4e", "TSVALUE")))

还值得在您的课程中添加__repr__,以便在您进行print调试时更轻松地查看正在发生的事情。

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'


class MainResult(db.Model):
    __tablename__ = "mainresult"

    metadata_key = db.Column(db.String(128), primary_key=True)
    individualResults = db.relationship('IndividualResult', backref='mainresult', lazy='dynamic',
                                        cascade="all, delete-orphan")

    def __init__(self, metadata_key):
        self.metadata_key = metadata_key

    def __repr__(self):
        return '<MR:{}>'.format(self.metadata_key)


class IndividualResult(db.Model):
    __tablename__ = "individualresult"

    metadata_key = db.Column(db.String(128), db.ForeignKey('mainresult.metadata_key'), primary_key=True)
    ts = db.Column(db.String(50), primary_key=True)

    def __init__(self, metadata_key, ts):
        self.metadata_key = metadata_key
        self.ts = ts

    def __repr__(self):
        return '<IQ:{}>'.format(self.metadata_key)


@app.route('/')
def hello_world():
    print MainResult.query.get("12345")
    # <MR:12345>
    print IndividualResult.query.get(("12345", "AAA"))
    # <IQ:12345>
    print IndividualResult.query.filter_by(metadata_key='12345').first()
    # <IQ:12345>
    return 'Hello World!'


# Populate with some test data:
@app.before_first_request
def data():
    db.create_all()
    mr = MainResult(metadata_key='12345')
    ir = IndividualResult(metadata_key='12345', ts='AAA')
    db.session.add(mr)
    db.session.add(ir)
    db.session.commit()

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