tet.sqlalchemy.simple module

Simple SQLAlchemy session setup with transaction management.

This module provides utilities for setting up SQLAlchemy with Pyramid, including transaction management via pyramid_tm and dependency injection via pyramid_di.

Features

  • Automatic session lifecycle tied to request

  • Transaction management with automatic commit/rollback

  • Alembic-friendly naming conventions for constraints

  • Dependency injection of sessions via pyramid_di

Example

Basic setup:

from tet.config import application_factory
from tet.sqlalchemy.simple import declarative_base

Base = declarative_base()

@application_factory(included_features=["services"])
def main(config):
    config.include("tet.sqlalchemy.simple")
    config.setup_sqlalchemy()
    config.scan()

Accessing the session in views:

from pyramid.view import view_config
from sqlalchemy.orm import Session

@view_config(route_name="users", renderer="json")
def list_users(request):
    session = request.find_service(Session)
    return [u.to_dict() for u in session.query(User).all()]
tet.sqlalchemy.simple.declarative_base(*, metadata=<object object>, naming_convention=<object object>) Any[source]

Create a declarative base, using the given naming convention, defaulting to the DEFAULT_NAMING_CONVENTION of this module

Returns:

the newly created declarative_base

tet.sqlalchemy.simple.get_tm_session(session_factory, transaction_manager)[source]

Get a sqlalchemy.orm.Session instance backed by a transaction.

This function will hook the session to the transaction manager which will take care of committing any changes.

  • When using pyramid_tm it will automatically be committed or aborted depending on whether an exception is raised.

  • When using scripts you should wrap the session in a manager yourself. For example:

    import transaction
    
    engine = get_engine(settings)
    session_factory = get_session_factory(engine)
    with transaction.manager:
        dbsession = get_tm_session(session_factory, transaction.manager)
    
tet.sqlalchemy.simple.includeme(config: Configurator) None[source]

Include the simple SQLAlchemy configuration with reasonable defaults.

Parameters:

config – the configurator

tet.sqlalchemy.simple.setup_sqlalchemy(config: Configurator, *, settings: dict | None = <object object>, prefix: str = 'sqlalchemy.', engine: sqlalchemy.Engine | None = <object object>, name: str = '') None[source]

Sets up SQLAlchemy, creating a request scoped service for the ORM session. Include all models before calling this configurator.

Parameters:
  • config – the configurator

  • base – The declarative base class. Required

  • settings – Optional settings dictionary for the engine creation

  • prefix – Optional settings prefix for the engine settings

  • engine – The engine to use - if specified, settings must not be given, or vice versa

  • name – the alternate name for which to bind the session service