Skip to content

Instantly share code, notes, and snippets.

@Goldziher
Last active January 3, 2022 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Goldziher/2d37bd5ad335ac103836ee4e9454cf39 to your computer and use it in GitHub Desktop.
Save Goldziher/2d37bd5ad335ac103836ee4e9454cf39 to your computer and use it in GitHub Desktop.
from os import environ
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
# we first define a dependency. The dependency is a function or method (async or sync) whose return value will be injected
def create_postgres_connection() -> AsyncEngine:
postgres_connection_string = environ.get("POSTGRES_CONNECTION_STRING", "")
if not postgres_connection_string:
raise ValueError("Missing ENV Variable POSTGRES_CONNECTION_STRING")
return create_async_engine(postgres_connection_string)
from sqlalchemy.ext.asyncio import AsyncEngine
from starlite import get
# a dependency is a kwarg - in this case "connection". The dependency needs to be mapped to the kwarg on some
# of the application.
@get("/some-path")
async def my_route_handler(connection: AsyncEngine) -> None:
...
from starlite import Starlite, Provide
from dependencies import create_postgres_connection
from route_handler import my_route_handler
# when instantiating the app we declare the dependency, mapping it to the key "connection". We also cache it, so the
# engine will be created once and not on every call.
app = Starlite(
route_handlers=[my_route_handler],
dependencies={
"connection": Provide(create_postgres_connection, use_cache=True)
},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment