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())
Metadata
Release files for af-db-session 0.0.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| af_db_session-0.0.3.tar.gz | 10.7 kB | With provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| af_db_session-0.0.3-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 23.2 kB
Release files / af_db_session-0.0.3.tar.gz
| Download URL | af_db_session-0.0.3.tar.gz |
|---|---|
| Size | 10.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e4e4d74ffbd48597323cc60cdbf05d6cf74c8b529729022628a9eff65695670a
|
|
BLAKE2b-256 checksum How to use checksums |
4ef730e4bc7f6dc31fd841936d19414d56061412099af0a897fbe6df3517ac49
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 4, 2026.
Transparency logRelease files / af_db_session-0.0.3-py3-none-any.whl
| Download URL | af_db_session-0.0.3-py3-none-any.whl |
|---|---|
| Size | 12.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7138f47d1e52fb0db7bb196a3171f028aeecff2f9765f3b8b7221131add732b0
|
|
BLAKE2b-256 checksum How to use checksums |
6c3adba68e94ec4ab9e139d687b409dc81d763ff13a5fa009118ce9f808a3a8f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 4, 2026.
Transparency logSecurity for af-db-session 0.0.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
All 2 files in this release have been uploaded with provenance metadata.
Attestation for af_db_session-0.0.3.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 4, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.