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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
82b77334fee361641f76b12a2d4679f624c68838ecabfb3b40a2783aedcce9a7
|
|
| MD5 |
04a6eaec372ddb433d695716b5076ce6
|
|
| BLAKE2b-256 |
4099e3f35cbb939f648b762b02a41c6cb9a40e40a646fb79f5606c014afec9d7
|
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
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
af_db_session-0.0.1.tar.gz -
Subject digest:
82b77334fee361641f76b12a2d4679f624c68838ecabfb3b40a2783aedcce9a7 - Sigstore transparency entry: 1473732931
- Sigstore integration time:
-
Permalink:
travelallfly/allfly-py-libs@11150745c5c1b67d74dc1a26ecd2aa6eda7cd08b -
Branch / Tag:
refs/heads/master - Owner: https://github.com/travelallfly
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
af-db-session-publish.yml@11150745c5c1b67d74dc1a26ecd2aa6eda7cd08b -
Trigger Event:
workflow_dispatch
-
Statement type:
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dc6a70cf186a696ed80aad2c8bf247fcc0b2aa326e9a4d7e9ffaf5a000c4176a
|
|
| MD5 |
5d7df44c9ae6318c5b98c7386674b832
|
|
| BLAKE2b-256 |
65567f9e77e286bcce7d70ca1851e901c041cbecc82bfa513dfcc35a9a6a458c
|
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
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
af_db_session-0.0.1-py3-none-any.whl -
Subject digest:
dc6a70cf186a696ed80aad2c8bf247fcc0b2aa326e9a4d7e9ffaf5a000c4176a - Sigstore transparency entry: 1473733002
- Sigstore integration time:
-
Permalink:
travelallfly/allfly-py-libs@11150745c5c1b67d74dc1a26ecd2aa6eda7cd08b -
Branch / Tag:
refs/heads/master - Owner: https://github.com/travelallfly
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
af-db-session-publish.yml@11150745c5c1b67d74dc1a26ecd2aa6eda7cd08b -
Trigger Event:
workflow_dispatch
-
Statement type: