July 28, 2017

November 25, 2019

Integrate SQLAlchemy with Falcon framework

To integrate SQLAlchemy with Falcon framework we can use middleware component. I will show you how to create a simple middleware which will create a session for every request and roll back changes if something fails.

Create engine, session_factory and scoped_session object.

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
import settings
engine = create_engine(
session_factory = sessionmaker(bind=engine)
Session = scoped_session(session_factory)

Create middleware.

class SQLAlchemySessionManager:
Create a scoped session for every request and close it when the request
def __init__(self, Session):
self.Session = Session
def process_resource(self, req, resp, resource, params):
resource.session = self.Session()
def process_response(self, req, resp, resource, req_succeeded):
if hasattr(resource, 'session'):
if not req_succeeded:

Register middleware.

import falcon
app = falcon.API(middleware=[

Session is accessible for every request.

import falcon
class MyAPI:
def on_get(self, req, resp):
# You can access self.session here
# self.session.add(foo)
# self.session.commit()
© 2020 Przemysław Kołodziejczyk