Falcon Middleware: SQLAlchemy Integration
falcon-sqla package provides a middleware component for managing
The manager component can also serve as a base building block or a recipe for
more complex use cases, such as applications leveraging multiple database
$ pip install falcon-sqla
Manager can be used in two ways:
- As a Falcon middleware component
- As a context manager to explicitly provide a database session
- Create a SQLAlchemy engine.
- Pass the engine to the
Manager()initializer as its first parameter.
- If using the manager as a middleware component, pass its
middlewareproperty to the
falcon.API()(to be renamed to
falcon.Appin Falcon 3.0+) initializer:
engine = create_engine('dialect+driver://my/database') manager = falcon_sqla.Manager(engine) app = falcon.API(middleware=[manager.middleware]) # The database session will be available as req.context.session
falcon_sqla.Manager can also explicitly provide a database session using
session_scope() context manager:
# Somewhere inside a responder with self.manager.session_scope(req, resp) as session: # Use the session # <...>
session_scope() can also be used as a standalone session context outside of
the request-response cycle:
with self.manager.session_scope() as session: # Use the session # <...>
Custom Vertical Partitioning
Simple random selection of read- and write- database replicas is supported
out of the box. Use the
add_engine() method to instruct the
include the provided engines in the runtime bind selection logic:
manager = falcon_sqla.Manager(engine) read_replica = create_engine('dialect+driver://my/database.replica') manager.add_engine(read_replica, 'r')
Manager.get_bind() method can be overridden to implement custom engine
selection logic for more complex use cases.
See also this SQLAlchemy recipe: Custom Vertical Partitioning.
Falcon is the minimalist web API framework for building reliable, correct, and high-performance REST APIs, microservices, proxies, and app backends in Python.
SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.