jds
jds

Reputation: 8279

Can I use Flask-SQLAlchemy and SQLAlchemy at the same time?

I've been using Flask-SQLAlchemy for a project for about a year. I like that it abstract away the sessioning for me. But now I need more granular control over my sessioning, namely to make a DB connection in a thread after the user has left my application. Is it possible / are there any dangers to use both Flask-SQLAlchemy and SQLAlchemy at the same time?

Bonus: if I must revert to just SQLAlchemy, what must I know? Is it just session scope?

EDIT trying detached session:

(pdb) db
<SQLAlchemy engine=None>
(Pdb) db.session
<sqlalchemy.orm.scoping.scoped_session object at 0x104b81210>
(Pdb) db.session()
*** RuntimeError: application not registered on db instance and no application bound to current context

Upvotes: 1

Views: 637

Answers (1)

Kijewski
Kijewski

Reputation: 26043

You have an app like:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

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

Currently you use:

@app.route('/add-some-item', method=['POST'])
def add_some_item():
    some_item = SomeItem(foo=request.form.get('foo'))
    db.session.add(some_item)
    db.session.commit()
    return 'The new id is: {}'.format(some_item.id)

But you can also use:

def i_run_in_some_other_thread():
    # no need for a Flask request context, just use:
    session = db.session()  # a bare SQLAlchemy session
    ...
    some_item = SomeItem(foo=bar)
    session.add(some_item)
    session.commit()

@app.route('/do-a-cron-job')
def do_a_cron_job()
    Thread(target=i_run_in_some_other_thread).start()
    return 'Thread started.'

By default a session is bound to a thread. For this simple case you don't need to do any changes to your code at all, but if sessions are shared between threads, then you would need to do a few changes: “Session and sessionmaker()”.

Just don't share sessions or objects between threads I'd say, or things will get messy. Share IDs and you're fine.

Upvotes: 2

Related Questions