librelist archives

« back to archive

Adding Flask-SQLAlchemy to an existing SA app

Adding Flask-SQLAlchemy to an existing SA app

From:
Luca Lesinigo
Date:
2011-11-04 @ 15:14
Hello there.

I already have an app that's using SQLAlchemy (with declarative) and I'm 
adding a web frontend to it;  to achieve that I added a new python module 
inside the app containing all the web code and I'll write that using Flask
(and possibly Flask-login and Flask-Principal, at least that's what I plan
to do ;)

The 'app' is actually structured like a python module because it will get 
used both as a module imported by other things or as a standalone app (it 
has both __init__.py and a bunch of run.py-like scripts at the top level).
When the app is loaded (import'ed) by Python it will do some setup things 
and *after* that it'll import the model and start up the SA things. After 
that it will eventually spawn some threads for its various moving parts 
(each in its own python submodule), the web frontend is one of those. So 
far for keeping things very modular.
The core of the app could be a python module itself and the threads could 
be external python apps that import the former - actually we're thinking 
to refactor it that way in the future, but that's another story.

The multiple threads of execution do, AFAIK, force us to use SQLAlchemy's 
scoped_session() instead of a standard session. Long story short, when the
web module gets loaded we already have SQLAlchemy initialized and a 
scoped_session() already created.

We also have a requirement that the core must work with just the base 
library and SQLAlchemy. This means we just can't import Flask-SQLAlchemy 
and use its SQLAlchemy object to derive the model classes from.

The big question is, can we still take advantage of Flask-SQLAlchemy by 
passing it our existing SQLAlchemy model/session/scoped_session/whatever ?

And if we can't use it, what are the main drawbacks we'll have when 
developing the web part? Looking at 
http://flask.pocoo.org/docs/patterns/sqlalchemy/ it seems it's just a 
matter of setting up session removal at @app.teardown_request and not much
else (given that we already handle all of SQLAlchemy configuration and 
setting up).

Thanks to all.
--
Luca Lesinigo