Skip to content

starlite-saqlalchemy

Starlite, SQLAlchemy 2.0 and SAQ configuration plugin.

Simple Example
"""The minimal Starlite/starlite-saqlalchemy application."""
from starlite import Starlite, get

from starlite_saqlalchemy import ConfigureApp


@get("/example")
def example_handler() -> dict:
    """Hello, world!"""
    return {"hello": "world"}


app = Starlite(route_handlers=[example_handler], on_app_init=[ConfigureApp()])

Configuration via environment.

Example .env
# App
BUILD_NUMBER=
DEBUG=true
ENVIRONMENT=
LOG_LEVEL=INFO
NAME=my-starlite-app

# API
API_CACHE_EXPIRATION=60
API_DEFAULT_PAGINATION_LIMIT=100
API_HEALTH_PATH=/health
API_DB_SESSION_DEPENDENCY_KEY=db_session

# OpenAPI
OPENAPI_CONTACT_EMAIL=some_human@email.com
OPENAPI_CONTACT_NAME="Some Human"
OPENAPI_TITLE="My Starlite App"
OPENAPI_VERSION=1.0.0

# Sentry
SENTRY_DSN=
SENTRY_TRACES_SAMPLE_RATE=0.0001

# Redis
REDIS_URL=redis://cache.local:6379/0

# Database
DB_ECHO=false
DB_ECHO_POOL=false
DB_POOL_DISABLE=false
DB_POOL_MAX_OVERFLOW=10
DB_POOL_SIZE=5
DB_POOL_TIMEOUT=30
DB_URL=postgresql+asyncpg://postgres:mysecretpassword@pg.db.local:5432/db

Pattern

sequenceDiagram
  Client ->> Controller: Inbound request data
  Controller ->> Service: Invoke service with data validated by DTO
  Service ->> Repository: View or modify the collection
  Repository ->> Service: Detached SQLAlchemy instance(s)
  Service ->> Queue: Enqueue async callback
  Service ->> Controller: Outbound data
  Controller ->> Client: Serialize via DTO
  Queue ->> Worker: Worker invoked
  Worker ->> Service: Makes async callback
  • Request data is deserialized and validated by Starlite before it is received by controller.
  • Controller invokes relevant service object method and waits for response.
  • Service method handles business logic of the request and triggers an asynchronous callback.
  • Service method returns to controller and response is made to client.
  • Async worker makes callback to service object where any async tasks can be performed. Depending on architecture, this may not even be the same instance of the application that handled the request.