Skip to content

Commit d36b50f

Browse files
Merge pull request #118 from developmentseed/updateRasterVectorPydantic1.0
update titiler-pgstac and tipg to last version compatible with pydantic 1.0
2 parents 7b429e8 + 5df83ce commit d36b50f

File tree

9 files changed

+94
-82
lines changed

9 files changed

+94
-82
lines changed

.github/workflows/tests/test_raster.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def test_mosaic_api():
3030
assert list(resp.json()[0]) == ["id", "bbox", "assets", "collection"]
3131
assert resp.json()[0]["id"] == "20200307aC0853900w361030"
3232

33-
resp = httpx.get(f"{raster_endpoint}/mosaic/{searchid}/15/8589/12849/assets")
33+
resp = httpx.get(f"{raster_endpoint}/mosaic/{searchid}/tiles/15/8589/12849/assets")
3434
assert resp.status_code == 200
3535
assert len(resp.json()) == 1
3636
assert list(resp.json()[0]) == ["id", "bbox", "assets", "collection"]

infrastructure/aws/handlers/raster_handler.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,18 @@
66

77
from eoapi.raster.app import app
88
from mangum import Mangum
9+
from titiler.pgstac.db import connect_to_db
910

1011
logging.getLogger("mangum.lifespan").setLevel(logging.ERROR)
1112
logging.getLogger("mangum.http").setLevel(logging.ERROR)
1213

14+
15+
@app.on_event("startup")
16+
async def startup_event() -> None:
17+
"""Connect to database on startup."""
18+
await connect_to_db(app)
19+
20+
1321
handler = Mangum(app, lifespan="off")
1422

1523
if "AWS_EXECUTION_ENV" in os.environ:

infrastructure/aws/handlers/stac_handler.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,18 @@
66

77
from eoapi.stac.app import app
88
from mangum import Mangum
9+
from stac_fastapi.pgstac.db import connect_to_db
910

1011
logging.getLogger("mangum.lifespan").setLevel(logging.ERROR)
1112
logging.getLogger("mangum.http").setLevel(logging.ERROR)
1213

14+
15+
@app.on_event("startup")
16+
async def startup_event() -> None:
17+
"""Connect to database on startup."""
18+
await connect_to_db(app)
19+
20+
1321
handler = Mangum(app, lifespan="off")
1422

1523
if "AWS_EXECUTION_ENV" in os.environ:

runtime/eoapi/raster/eoapi/raster/app.py

Lines changed: 57 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""TiTiler+PgSTAC FastAPI application."""
22

33
import logging
4+
from contextlib import asynccontextmanager
45
from typing import Dict
56

67
import pystac
@@ -17,7 +18,6 @@
1718
from titiler.core.errors import DEFAULT_STATUS_CODES, add_exception_handlers
1819
from titiler.core.factory import AlgorithmFactory, MultiBaseTilerFactory, TMSFactory
1920
from titiler.core.middleware import CacheControlMiddleware
20-
from titiler.core.resources.enums import OptionalHeader
2121
from titiler.mosaic.errors import MOSAIC_STATUS_CODES
2222
from titiler.pgstac.db import close_db_connection, connect_to_db
2323
from titiler.pgstac.dependencies import ItemPathParams
@@ -40,19 +40,53 @@
4040
templates = Jinja2Templates(directory=str(resources_files(__package__) / "templates")) # type: ignore
4141

4242

43-
if settings.debug:
44-
optional_headers = [OptionalHeader.server_timing, OptionalHeader.x_assets]
45-
else:
46-
optional_headers = []
43+
@asynccontextmanager
44+
async def lifespan(app: FastAPI):
45+
"""FastAPI Lifespan."""
46+
# Create Connection Pool
47+
await connect_to_db(app)
48+
yield
49+
# Close the Connection Pool
50+
await close_db_connection(app)
51+
4752

48-
app = FastAPI(title=settings.name, version=eoapi_raster_version)
53+
app = FastAPI(
54+
title=settings.name,
55+
version=eoapi_raster_version,
56+
root_path=settings.root_path,
57+
lifespan=lifespan,
58+
)
4959
add_exception_handlers(app, DEFAULT_STATUS_CODES)
5060
add_exception_handlers(app, MOSAIC_STATUS_CODES)
5161

62+
if settings.cors_origins:
63+
app.add_middleware(
64+
CORSMiddleware,
65+
allow_origins=settings.cors_origins,
66+
allow_credentials=True,
67+
allow_methods=["GET", "POST", "OPTIONS"],
68+
allow_headers=["*"],
69+
)
70+
71+
app.add_middleware(
72+
CacheControlMiddleware,
73+
cachecontrol=settings.cachecontrol,
74+
exclude_path={r"/healthz"},
75+
)
76+
app.add_middleware(
77+
CompressionMiddleware,
78+
exclude_mediatype={
79+
"image/jpeg",
80+
"image/jpg",
81+
"image/png",
82+
"image/jp2",
83+
"image/webp",
84+
},
85+
)
86+
5287
###############################################################################
5388
# MOSAIC Endpoints
5489
mosaic = MosaicTilerFactory(
55-
optional_headers=optional_headers,
5690
router_prefix="/mosaic",
5791
add_statistics=True,
5892
# add /map viewer
@@ -93,7 +127,6 @@ async def list_collection(request: Request):
93127
stac = MultiBaseTilerFactory(
94128
reader=PgSTACReader,
95129
path_dependency=ItemPathParams,
96-
optional_headers=optional_headers,
97130
router_prefix="/collections/{collection_id}/items/{item_id}",
98131
# add /map viewer
99132
add_viewer=True,
@@ -178,25 +211,37 @@ def landing(request: Request):
178211
"rel": "service-doc",
179212
},
180213
{
181-
"title": "Mosaic List (JSON)",
214+
"title": "STAC Item Asset's Info (template URL)",
215+
"href": stac.url_for(request, "info"),
216+
"type": "application/json",
217+
"rel": "data",
218+
},
219+
{
220+
"title": "STAC Item Viewer (template URL)",
221+
"href": stac.url_for(request, "viewer"),
222+
"type": "text/html",
223+
"rel": "data",
224+
},
225+
{
226+
"title": "STAC Mosaic List (JSON)",
182227
"href": mosaic.url_for(request, "list_mosaic"),
183228
"type": "application/json",
184229
"rel": "data",
185230
},
186231
{
187-
"title": "Mosaic Builder",
232+
"title": "STAC Mosaic Builder",
188233
"href": mosaic.url_for(request, "mosaic_builder"),
189234
"type": "text/html",
190235
"rel": "data",
191236
},
192237
{
193-
"title": "Mosaic Metadata (template URL)",
238+
"title": "STAC Mosaic Metadata (template URL)",
194239
"href": mosaic.url_for(request, "info_search", searchid="{searchid}"),
195240
"type": "application/json",
196241
"rel": "data",
197242
},
198243
{
199-
"title": "Mosaic viewer (template URL)",
244+
"title": "STAC Mosaic viewer (template URL)",
200245
"href": mosaic.url_for(request, "map_viewer", searchid="{searchid}"),
201246
"type": "text/html",
202247
"rel": "data",
@@ -240,41 +285,3 @@ def landing(request: Request):
240285
"urlparams": str(request.url.query),
241286
},
242287
)
243-
244-
245-
if settings.cors_origins:
246-
app.add_middleware(
247-
CORSMiddleware,
248-
allow_origins=settings.cors_origins,
249-
allow_credentials=True,
250-
allow_methods=["GET", "POST", "OPTIONS"],
251-
allow_headers=["*"],
252-
)
253-
254-
app.add_middleware(
255-
CacheControlMiddleware,
256-
cachecontrol=settings.cachecontrol,
257-
exclude_path={r"/healthz"},
258-
)
259-
app.add_middleware(
260-
CompressionMiddleware,
261-
exclude_mediatype={
262-
"image/jpeg",
263-
"image/jpg",
264-
"image/png",
265-
"image/jp2",
266-
"image/webp",
267-
},
268-
)
269-
270-
271-
@app.on_event("startup")
272-
async def startup_event() -> None:
273-
"""Connect to database on startup."""
274-
await connect_to_db(app)
275-
276-
277-
@app.on_event("shutdown")
278-
async def shutdown_event() -> None:
279-
"""Close database connection."""
280-
await close_db_connection(app)
Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
"""API settings."""
22

3-
from functools import lru_cache
4-
53
import pydantic
64

75

8-
class _ApiSettings(pydantic.BaseSettings):
6+
class ApiSettings(pydantic.BaseSettings):
97
"""API settings"""
108

119
name: str = "eoAPI-raster"
1210
cors_origins: str = "*"
1311
cachecontrol: str = "public, max-age=3600"
1412
debug: bool = False
13+
root_path: str = ""
1514

1615
@pydantic.validator("cors_origins")
1716
def parse_cors_origin(cls, v):
@@ -23,16 +22,3 @@ class Config:
2322

2423
env_file = ".env"
2524
env_prefix = "EOAPI_RASTER_"
26-
27-
28-
@lru_cache()
29-
def ApiSettings() -> _ApiSettings:
30-
"""
31-
This function returns a cached instance of the APISettings object.
32-
Caching is used to prevent re-reading the environment every time the API settings are used in an endpoint.
33-
If you want to change an environment variable and reset the cache (e.g., during testing), this can be done
34-
using the `lru_cache` instance method `get_api_settings.cache_clear()`.
35-
36-
From https://github.com/dmontagu/fastapi-utils/blob/af95ff4a8195caaa9edaa3dbd5b6eeb09691d9c7/fastapi_utils/api_settings.py#L60-L69
37-
"""
38-
return _ApiSettings()

runtime/eoapi/raster/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ classifiers = [
1919
]
2020
dynamic = ["version"]
2121
dependencies = [
22-
"titiler.pgstac==0.4.1",
22+
"titiler.pgstac==0.5.1",
2323
"starlette-cramjam>=0.3,<0.4",
2424
"importlib_resources>=1.1.0;python_version<'3.9'",
2525
]

runtime/eoapi/stac/eoapi/stac/app.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""FastAPI application using PGStac."""
22

3+
from contextlib import asynccontextmanager
4+
35
from eoapi.stac.config import ApiSettings, TilesApiSettings
46
from eoapi.stac.config import extensions as PgStacExtensions
57
from eoapi.stac.config import get_request_model as GETModel
@@ -31,8 +33,18 @@
3133
settings = Settings()
3234

3335

36+
@asynccontextmanager
37+
async def lifespan(app: FastAPI):
38+
"""FastAPI Lifespan."""
39+
# Create Connection Pool
40+
await connect_to_db(app)
41+
yield
42+
# Close the Connection Pool
43+
await close_db_connection(app)
44+
45+
3446
api = StacApi(
35-
app=FastAPI(title=api_settings.name),
47+
app=FastAPI(title=api_settings.name, lifespan=lifespan),
3648
title=api_settings.name,
3749
description=api_settings.name,
3850
settings=settings,
@@ -69,15 +81,3 @@ async def viewer_page(request: Request):
6981
{"request": request, "endpoint": str(request.url).replace("/index.html", "")},
7082
media_type="text/html",
7183
)
72-
73-
74-
@app.on_event("startup")
75-
async def startup_event():
76-
"""Connect to database on startup."""
77-
await connect_to_db(app)
78-
79-
80-
@app.on_event("shutdown")
81-
async def shutdown_event():
82-
"""Close database connection."""
83-
await close_db_connection(app)

runtime/eoapi/stac/pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ classifiers = [
1919
]
2020
dynamic = ["version"]
2121
dependencies = [
22+
"fastapi>=0.95.1",
23+
"pydantic~=1.0",
24+
"geojson-pydantic~=0.6",
2225
"stac-fastapi.api~=2.4",
2326
"stac-fastapi.types~=2.4",
2427
"stac-fastapi.extensions~=2.4",

runtime/eoapi/vector/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ classifiers = [
1919
]
2020
dynamic = ["version"]
2121
dependencies = [
22-
"tipg==0.2.0",
22+
"tipg==0.3.0",
2323
]
2424

2525
[project.optional-dependencies]

0 commit comments

Comments
 (0)