Last active
January 3, 2022 13:03
-
-
Save Goldziher/2d37bd5ad335ac103836ee4e9454cf39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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