Skip to content

Instantly share code, notes, and snippets.

@agronholm
Last active August 29, 2015 14:01
Show Gist options
  • Save agronholm/84e4e31621e07b9e12f3 to your computer and use it in GitHub Desktop.
Save agronholm/84e4e31621e07b9e12f3 to your computer and use it in GitHub Desktop.
A minimal replacement for Flask-SQLAlchemy
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