|
4 | 4 |
|
5 | 5 | import asyncio
|
6 | 6 | import os
|
| 7 | +from functools import lru_cache |
7 | 8 |
|
8 | 9 | from mangum import Mangum
|
9 | 10 | from utils import get_secret_dict
|
10 | 11 |
|
11 |
| -pgstac_secret_arn = os.environ["PGSTAC_SECRET_ARN"] |
12 | 12 |
|
13 |
| -secret = get_secret_dict(pgstac_secret_arn) |
| 13 | +@lru_cache(maxsize=1) |
| 14 | +def get_db_credentials(): |
| 15 | + """Cache the credentials to avoid repeated Secrets Manager calls.""" |
| 16 | + pgstac_secret_arn = os.environ.get("PGSTAC_SECRET_ARN") |
| 17 | + if not pgstac_secret_arn: |
| 18 | + raise ValueError("PGSTAC_SECRET_ARN is not set!") |
| 19 | + return get_secret_dict(pgstac_secret_arn) |
| 20 | + |
| 21 | + |
| 22 | +secret = get_db_credentials() |
14 | 23 | os.environ.update(
|
15 | 24 | {
|
16 | 25 | "postgres_host": secret["host"],
|
|
20 | 29 | "postgres_port": str(secret["port"]),
|
21 | 30 | }
|
22 | 31 | )
|
| 32 | + |
23 | 33 | from titiler.pgstac.db import connect_to_db # noqa: E402
|
24 | 34 | from titiler.pgstac.main import app # noqa: E402
|
25 |
| -from titiler.pgstac.settings import PostgresSettings |
26 | 35 |
|
27 | 36 |
|
28 | 37 | @app.on_event("startup")
|
29 | 38 | async def startup_event() -> None:
|
30 | 39 | """Connect to database on startup."""
|
31 |
| - pgstac_secret_arn = os.getenv("PGSTAC_SECRET_ARN") |
32 |
| - if not pgstac_secret_arn: |
33 |
| - raise ValueError("PGSTAC_SECRET_ARN is not set!") |
34 |
| - |
35 |
| - secret = get_secret_dict(pgstac_secret_arn) |
36 |
| - await connect_to_db( |
37 |
| - app, |
38 |
| - settings=PostgresSettings( |
39 |
| - postgres_user=secret["username"], |
40 |
| - postgres_pass=secret["password"], |
41 |
| - postgres_host=secret["host"], |
42 |
| - postgres_port=secret["port"], |
43 |
| - postgres_dbname=secret["dbname"], |
44 |
| - ), |
45 |
| - ) |
| 40 | + await connect_to_db(app) |
46 | 41 |
|
47 | 42 |
|
48 | 43 | handler = Mangum(app, lifespan="off")
|
|
0 commit comments