Skip to content

Instantly share code, notes, and snippets.

@danielrichman
Last active May 19, 2017 16:30
Show Gist options
  • Save danielrichman/9dd57a64319288d7678a to your computer and use it in GitHub Desktop.
Save danielrichman/9dd57a64319288d7678a to your computer and use it in GitHub Desktop.
Flask-Micro-SQLAlchemy

The setup:

  • A library uses SQLAlchemy (openly)

  • Want to write a Flask webapp, using the sessionmaker exposed by the library (say, some module database that looks like this):

    engine = create_engine("....")
    Session = sessionmaker(bind=engine)

It might be possible to use Flask-SQLAlchemy here, but this is simpler. The code snippet is extracted from sections of Flask-SQLAlchemy.

# Extracted from Flask-SQLAlchemy
sess = sqlalchemy.orm.scoped_session(
database.Session,
scopefunc=flask._app_ctx_stack.__ident_func__
)
@app.teardown_appcontext
def teardown_appcontext(res):
session.remove()
return res
# or _request_ctx_stack, teardown_request for Flask <= 0.8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment