Last active
August 29, 2015 14:01
-
-
Save agronholm/84e4e31621e07b9e12f3 to your computer and use it in GitHub Desktop.
A minimal replacement for Flask-SQLAlchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy.engine import create_engine | |
from sqlalchemy.orm.scoping import scoped_session | |
from sqlalchemy.orm.session import sessionmaker | |
class SQLAlchemy: | |
def __init__(self, app=None): | |
if app is not None: | |
self.init_app(app) | |
def init_app(self, app): | |
def add_kwarg(arg, option): | |
if option in app.config: | |
kwargs[arg] = app.config[option] | |
self.app = app | |
if not hasattr(app, 'extensions'): | |
app.extensions = {} | |
app.extensions['sqlalchemy'] = self | |
kwargs = {} | |
add_kwarg('pool_size', 'SQLALCHEMY_POOL_SIZE') | |
add_kwarg('max_overflow', 'SQLALCHEMY_MAX_OVERFLOW') | |
self.engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], **kwargs) | |
self.session = scoped_session(sessionmaker(self.engine)) | |
app.teardown_appcontext(self.close_session) | |
def close_session(self, exc): | |
try: | |
if exc is None: | |
self.session.commit() | |
finally: | |
self.session.remove() | |
return exc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment