Skip to main content

A configurable DB session factory

Project description

af-db-session

A configurable PostgreSQL session factory for Python applications. Wraps SQLAlchemy connection pool setup and pydantic-settings configuration into a single reusable package — install it, point it at your .env, and get sessions.

Installation

pip install af-db-session
# or with Poetry:
poetry add af-db-session

A PostgreSQL driver is not included — install whichever you prefer alongside it:

pip install psycopg2-binary   # most common
pip install psycopg           # psycopg3

Quickstart

from allfly.db.session import DatabaseSettings, build_session_factory

settings = DatabaseSettings()           # reads DB_* vars from .env
factory = build_session_factory(settings)

session = factory.get_session()
try:
    result = session.execute(...)
    session.commit()
finally:
    session.close()

# On app shutdown
factory.close()

Configuration

All settings are loaded from environment variables with a DB_ prefix. By default the library reads from a .env file in the working directory.

Environment variables

Variable Default Description
DB_HOST localhost Primary database host
DB_PORT 5432 Database port
DB_DATABASE postgres Database name
DB_USERNAME postgres Database username
DB_PASSWORD postgres Database password
DB_SCHEMA_NAME public PostgreSQL schema (used for search_path)
DB_DRIVER psycopg2 SQLAlchemy driver name
DB_RO_HOST (unset) Read-only replica host; falls back to DB_HOST
DB_POOL_SIZE 10 Minimum connections in pool
DB_MAX_POOL_SIZE 20 Maximum connections in pool
DB_POOL_TIMEOUT 30 Seconds to wait for a connection from pool
DB_POOL_RECYCLE 299 Recycle connections after this many seconds
DB_APPLICATION_NAME app Application name reported to PostgreSQL

Choosing your env file

# Standard .env (default)
settings = DatabaseSettings()

# Custom env file — e.g. .env.local, .env.production
settings = DatabaseSettings.from_env(".env.local")

# No file — reads only from real environment variables
settings = DatabaseSettings.from_env(None)

# No file, with inline overrides
settings = DatabaseSettings.from_env(None, host="db.internal", database="myapp")

Using a different driver

# psycopg3
settings = DatabaseSettings.from_env(".env", driver="psycopg")

# or via env var
# DB_DRIVER=psycopg

The driver value is used as the SQLAlchemy URL scheme: postgresql+{driver}://.... The corresponding package must be installed in your environment.

Read-only replica

from allfly.db.session import DatabaseSettings, build_ro_session_factory

settings = DatabaseSettings()       # set DB_RO_HOST to point at your replica
ro_factory = build_ro_session_factory(settings)

session = ro_factory.get_session()  # writes will be rejected by PostgreSQL

If DB_RO_HOST is not set, RODatabaseSessionFactory falls back to the primary host but still enforces read-only mode at the PostgreSQL level.

FastAPI example

from contextlib import asynccontextmanager
from fastapi import FastAPI
from allfly.db.session import DatabaseSettings, build_session_factory

settings = DatabaseSettings.from_env(".env.local")

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.db = build_session_factory(settings)
    yield
    app.state.db.close()

app = FastAPI(lifespan=lifespan)

@app.get("/items")
def list_items():
    session = app.state.db.get_session()
    try:
        return session.execute(...).all()
    finally:
        session.close()

Logging

The library emits to the allfly.db.session logger namespace using Python's standard logging module. To activate debug output:

import logging
logging.getLogger("allfly.db.session").setLevel(logging.DEBUG)

Routing to loguru

If your app uses loguru, intercept stdlib logging once at startup:

import logging
from loguru import logger

class InterceptHandler(logging.Handler):
    def emit(self, record: logging.LogRecord) -> None:
        logger.opt(depth=6, exception=record.exc_info).log(
            record.levelname, record.getMessage()
        )

logging.getLogger("allfly.db.session").addHandler(InterceptHandler())

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

af_db_session-0.0.1.tar.gz (5.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

af_db_session-0.0.1-py3-none-any.whl (6.8 kB view details)

Uploaded Python 3

File details

Details for the file af_db_session-0.0.1.tar.gz.

File metadata

  • Download URL: af_db_session-0.0.1.tar.gz
  • Upload date:
  • Size: 5.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for af_db_session-0.0.1.tar.gz
Algorithm Hash digest
SHA256 82b77334fee361641f76b12a2d4679f624c68838ecabfb3b40a2783aedcce9a7
MD5 04a6eaec372ddb433d695716b5076ce6
BLAKE2b-256 4099e3f35cbb939f648b762b02a41c6cb9a40e40a646fb79f5606c014afec9d7

See more details on using hashes here.

Provenance

The following attestation bundles were made for af_db_session-0.0.1.tar.gz:

Publisher: af-db-session-publish.yml on travelallfly/allfly-py-libs

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file af_db_session-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: af_db_session-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 6.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for af_db_session-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 dc6a70cf186a696ed80aad2c8bf247fcc0b2aa326e9a4d7e9ffaf5a000c4176a
MD5 5d7df44c9ae6318c5b98c7386674b832
BLAKE2b-256 65567f9e77e286bcce7d70ca1851e901c041cbecc82bfa513dfcc35a9a6a458c

See more details on using hashes here.

Provenance

The following attestation bundles were made for af_db_session-0.0.1-py3-none-any.whl:

Publisher: af-db-session-publish.yml on travelallfly/allfly-py-libs

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page