af-fastapi-db-txs
FastAPI integration for allfly.db.session.TransactionContext (from
af-db-session): request-scoped read-write and
read-only database sessions with automatic commit/rollback, so route handlers never manage
session lifecycle themselves.
No hidden global state, no DI framework coupling. Every component here takes its
TransactionContext and session factories as explicit arguments — your app owns
instantiation and lifecycle, and wires the same TransactionContext instance into the
middleware and any read-only dependencies it builds. auto_configure_database (from
af-db-session) builds all of them for you in one call, if you don't need custom factories.
Installation
pip install af-fastapi-db-txs
# or with Poetry:
poetry add af-fastapi-db-txs
Wiring it into your app
Your app should hold exactly one TransactionContext instance for the life of the process.
The easiest way to get one — along with its matching DatabaseSessionFactory/
RODatabaseSessionFactory — is auto_configure_database, from af-db-session:
from allfly.db.session import auto_configure_database, DatabaseAutoConfigurationProperties
from allfly.fastapi.db_txs import TransactionMiddleware, make_read_only_transaction
db = auto_configure_database(db_settings, DatabaseAutoConfigurationProperties(build_read_replica=True))
app.add_middleware(
TransactionMiddleware,
transaction_context=db.transaction_context,
session_factory=db.session_factory,
)
ReadOnlyTransaction = make_read_only_transaction(db.ro_session_factory, db.transaction_context)
If you'd rather assemble the pieces yourself (e.g. a custom DatabaseSessionFactory
subclass), build each one directly instead — TransactionMiddleware and
make_read_only_transaction only need a TransactionContext and the relevant factory,
however you got them:
from allfly.db.session import TransactionContext, build_session_factory, build_ro_session_factory
transaction_context = TransactionContext()
session_factory = build_session_factory(db_settings)
ro_session_factory = build_ro_session_factory(db_settings)
Using it in routes
Write routes (RW by default — the middleware opens a session for every request):
@router.post("/users")
def create_user(user_repo: UserRepositoryDI):
return user_repo.save(user) # commits automatically on a 2xx/3xx response
Read-only routes (route or router-level, targets your read replica instead):
@router.get("/users", dependencies=[ReadOnlyTransaction])
def search_users(user_repo: UserRepositoryDI) -> list[UserResponse]:
...
Wherever your app resolves a Session for its repositories, call
transaction_context.get_session() — it returns the RO session if one is active for the
current request, otherwise the RW session opened by the middleware, otherwise None.
Scripts and background tasks
For code outside a FastAPI request (management scripts, workers), use the context managers
directly instead of the middleware/dependency — either via the db object from
auto_configure_database:
with db.transaction():
user_repo = UserRepository(db.transaction_context.get_session())
user_repo.save(user)
# commits on success, rolls back on exception
with db.read_transaction():
result = repo.find(...)
or, if you built the pieces yourself, the same methods on TransactionContext directly:
with transaction_context.transaction(session_factory):
user_repo = UserRepository(transaction_context.get_session())
user_repo.save(user)
with transaction_context.read_transaction(ro_session_factory):
result = repo.find(...)
If a single DatabaseAutoConfiguration is truly the only one in the process (no multiple
databases, no multiple apps sharing the interpreter — e.g. in a pytest session), af-db-session
also has an opt-in allfly.db.session.default module for a bare with transaction(): — see
af-db-session's docs for when that tradeoff is worth it.
Why explicit injection?
This library has no knowledge of any dependency-injection framework. TransactionMiddleware
and make_read_only_transaction both take a TransactionContext and session factory
instances directly — if your app uses a DI container, wire these components into it yourself;
if it doesn't, pass the instances around as plain module-level values. Either way, the one
invariant that matters is sharing the same TransactionContext instance across the
middleware, any read-only dependencies, and your app's own session-resolution code — its
ContextVars are what tie a request's session together.
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_fastapi_db_txs-0.0.2.tar.gz.
File metadata
- Download URL: af_fastapi_db_txs-0.0.2.tar.gz
- Upload date:
- Size: 4.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
25974792b7b8b0961dd206fe97a276542ae0fe07a104492954619d6b8acd72d2
|
|
| MD5 |
5021c0fa9191fcadcb848e8a4fdacac7
|
|
| BLAKE2b-256 |
3c3d8399b22b78d28f00d58b44390f41d4d8cef6ae8e462ae6bd426dacd58ee3
|
Provenance
The following attestation bundles were made for af_fastapi_db_txs-0.0.2.tar.gz:
Publisher:
af-fastapi-db-txs-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_fastapi_db_txs-0.0.2.tar.gz -
Subject digest:
25974792b7b8b0961dd206fe97a276542ae0fe07a104492954619d6b8acd72d2 - Sigstore transparency entry: 2340378716
- Sigstore integration time:
-
Permalink:
travelallfly/allfly-py-libs@18f1937de7fecf87bae48579c1a9fb804304ac90 -
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-fastapi-db-txs-publish.yml@18f1937de7fecf87bae48579c1a9fb804304ac90 -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file af_fastapi_db_txs-0.0.2-py3-none-any.whl.
File metadata
- Download URL: af_fastapi_db_txs-0.0.2-py3-none-any.whl
- Upload date:
- Size: 5.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ab7f00fe8fee11cf58c1ffc9c6fcb338732b83710613daaa9f72ecd847d9599a
|
|
| MD5 |
1a4e66d42cefda827ef71c3b40cee693
|
|
| BLAKE2b-256 |
c03923ab8154953b76c38cc6bf03ab69c75b8e4da6ce5fd4e570d8719aa13993
|
Provenance
The following attestation bundles were made for af_fastapi_db_txs-0.0.2-py3-none-any.whl:
Publisher:
af-fastapi-db-txs-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_fastapi_db_txs-0.0.2-py3-none-any.whl -
Subject digest:
ab7f00fe8fee11cf58c1ffc9c6fcb338732b83710613daaa9f72ecd847d9599a - Sigstore transparency entry: 2340378731
- Sigstore integration time:
-
Permalink:
travelallfly/allfly-py-libs@18f1937de7fecf87bae48579c1a9fb804304ac90 -
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-fastapi-db-txs-publish.yml@18f1937de7fecf87bae48579c1a9fb804304ac90 -
Trigger Event:
workflow_dispatch
-
Statement type: