Pyramid Transaction Manager
pyramid_tm is a package that integrates the Python `transaction` package with the Pyramid web framework, allowing Pyramid requests to join the active transaction. It provides centralized transaction management for Pyramid applications without relying on external WSGI middleware. Maintained by the Pylons Project, it has a generally active release cadence, with version 2.6 released in November 2024.
Warnings
- breaking Version 2.6 dropped support for Python 3.7 and 3.8. Ensure your environment uses Python 3.9 or newer.
- breaking The behavior of the `tm.commit_veto` hook changed in version 2.2. It will now be consulted for squashed exceptions (exceptions handled by an exception view) instead of always aborting. It inspects `request.exception` and the response to determine whether to commit or abort.
- gotcha Accessing `request.tm` outside the `pyramid_tm` tween or during a request where `pyramid_tm` was explicitly disabled (e.g., via an activate hook or `tm.active` in WSGI environ for testing) will raise an `AttributeError`.
- gotcha If you manually complete a transaction using `request.tm.abort()` or `request.tm.commit()`, subsequent uses of the transaction manager within the same request will fail unless `request.tm.begin()` is explicitly invoked again to start a new transaction.
- gotcha If `repoze.tm` or `repoze.tm2` middleware is present in the WSGI pipeline, `pyramid_tm` becomes inactive. These middlewares handle transaction management themselves and conflict with `pyramid_tm`.
Install
-
pip install pyramid-tm
Imports
- pyramid_tm
config.include('pyramid_tm')
Quickstart
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
# Any database operations here would automatically join the active transaction
return Response('Hello World from pyramid_tm!')
if __name__ == '__main__':
with Configurator() as config:
config.include('pyramid_tm') # Enable pyramid_tm
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
print("Pyramid server running on http://0.0.0.0:6543")
server.serve_forever()