The db.Model
is a SQLAlchemy declarative_base()
, so you can use your models like even with plain SQLAlchemy.
This example works (YourModel
is a Flask-SQLAlchemy model):
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import settings
from models import YourModel
engine = create_engine(settings.SQLALCHEMY_DATABASE_URI)
Session = sessionmaker(bind=engine)
session = Session()
# do something with your session
session.query(YourModel).first()
You have to decouple db
from app
, so you can import it without triggering app
creation, using db.init_app
.
Of course you should be careful here. If you load your settings dynamically, maybe you'll load it from the wrong place with import settings
instead of current_app.config
, but looks like you already have your worker adressed, so it is not an issue for you.
Another option is create another Flask app instead of your huge web app.
From Flask-SQLAlchemy docs (http://pythonhosted.org/Flask-SQLAlchemy/api.html#flask.ext.sqlalchemy.SQLAlchemy):
You can still use sqlalchemy and sqlalchemy.orm directly, but note that Flask-SQLAlchemy customizations are available only through an instance of this SQLAlchemy class. Query classes default to BaseQuery for db.Query, db.Model.query_class, and the default query_class for db.relationship and db.backref. If you use these interfaces through sqlalchemy and sqlalchemy.orm directly, the default query class will be that of sqlalchemy.
EDIT: One additional thing to remember when mixing sqlalchemy session with flask-sqlalchemy models is that the flask-sqlalchemy session object is actually a subclass, with added _model_changes dictionary. As per this answer, you won't be able to commit the session if you don't add the _model_changes field:
def create_session(config):
engine = create_engine(config['DATABASE_URI'])
Session = sessionmaker(bind=engine)
session = Session()
session._model_changes = {}
return session