I have a daemon running that generates data and writes it to my database using Flask. I'm now building an API service on top of that same data, and I'm hoping to reuse my same models, but this doesn't seem to work as expected. Here's what my model code looks like:
from sqlalchemy import BigInteger, Column, DateTime, Float, ForeignKey, Index, Integer, String
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(200), nullable=False, unique=True)
...
But then when I try to call it from the Flask App:
from flask.ext.sqlalchemy import SQLAlchemy
from models import User
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'some_mysql_connect_str'
db = SQLAlchemy(app)
...
def get_users_named_bob():
return User.query.filter_by(name='bob')
I get: AttributeError: type object 'User' has no attribute 'query'
What's the best way of doing this?
Side note: I saw this question from about a year ago, but I'm hoping things have gotten better since then, since it seems a common use case.