Skip to content

Commit

Permalink
parse sub-model for table_settings
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentsarago committed Jan 9, 2024
1 parent 37fd514 commit 1d01330
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 19 deletions.
22 changes: 22 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,3 +558,25 @@ def app_functions(database_url, monkeypatch):

with TestClient(app) as client:
yield client


@pytest.fixture(autouse=True)
def app_public_table(database_url, monkeypatch):
"""Create app with connection to the pytest database."""
monkeypatch.setenv("TIPG_TABLE_CONFIG__public_landsat_wrs__properties", '["pr"]')

postgres_settings = PostgresSettings(database_url=database_url)
db_settings = DatabaseSettings(
schemas=["public"],
functions=[],
)
sql_settings = CustomSQLSettings(custom_sql_directory=None)

app = create_tipg_app(
postgres_settings=postgres_settings,
db_settings=db_settings,
sql_settings=sql_settings,
)

with TestClient(app) as client:
yield client
13 changes: 13 additions & 0 deletions tests/routes/test_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,16 @@ def test_item(app):
# not found
response = app.get("/collections/public.landsat_wrs/items/50000")
assert response.status_code == 404


def test_item_with_property_config(app_public_table):
"""Test /items/{item id} endpoint."""
response = app_public_table.get("/collections/public.landsat_wrs/items/1")
assert response.status_code == 200
assert response.headers["content-type"] == "application/geo+json"
body = response.json()
assert body["type"] == "Feature"
assert body["id"] == 1
assert body["links"]
print(body["properties"])
Item.model_validate(body)
18 changes: 6 additions & 12 deletions tipg/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from tipg.filter.filters import bbox_to_wkt
from tipg.logger import logger
from tipg.model import Extent
from tipg.settings import FeaturesSettings, MVTSettings, TableSettings
from tipg.settings import FeaturesSettings, MVTSettings, TableConfig, TableSettings

from fastapi import FastAPI

Expand Down Expand Up @@ -958,16 +958,16 @@ async def get_collection_index( # noqa: C901
if table_id == "pg_temp.tipg_catalog":
continue

table_conf = table_confs.get(confid, {})
table_conf = table_confs.get(confid, TableConfig())

# Make sure that any properties set in conf exist in table
properties = sorted(table.get("properties", []), key=lambda d: d["name"])
properties_setting = table_conf.get("properties", [])
properties_setting = table_conf.properties or []
if properties_setting:
properties = [p for p in properties if p["name"] in properties_setting]

# ID Column
id_column = table_conf.get("pk") or table.get("pk")
id_column = table_conf.pk or table.get("pk")
if not id_column and fallback_key_names:
for p in properties:
if p["name"] in fallback_key_names:
Expand All @@ -979,17 +979,11 @@ async def get_collection_index( # noqa: C901

for c in properties:
if c.get("type") in ("timestamp", "timestamptz", "date"):
if (
table_conf.get("datetimecol") == c["name"]
or datetime_column is None
):
if table_conf.datetimecol == c["name"] or datetime_column is None:
datetime_column = c

if c.get("type") in ("geometry", "geography"):
if (
table_conf.get("geomcol") == c["name"]
or geometry_column is None
):
if table_conf.geomcol == c["name"] or geometry_column is None:
geometry_column = c

catalog[table_id] = Collection(
Expand Down
25 changes: 18 additions & 7 deletions tipg/settings.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
"""tipg config."""

import json
import pathlib
from typing import Dict, List, Optional
from typing import Any, Dict, List, Optional

from pydantic import (
BaseModel,
DirectoryPath,
Field,
PostgresDsn,
Expand All @@ -12,7 +14,6 @@
model_validator,
)
from pydantic_settings import BaseSettings
from typing_extensions import TypedDict


class APISettings(BaseSettings):
Expand All @@ -36,13 +37,23 @@ def parse_cors_origin(cls, v):
return [origin.strip() for origin in v.split(",")]


class TableConfig(TypedDict, total=False):
class TableConfig(BaseModel):
"""Configuration to add table options with env variables."""

geomcol: Optional[str]
datetimecol: Optional[str]
pk: Optional[str]
properties: Optional[List[str]]
geomcol: Optional[str] = None
datetimecol: Optional[str] = None
pk: Optional[str] = None
properties: Optional[List[str]] = None

model_config = {"extra": "ignore"}

@field_validator("properties", mode="before")
def _properties(cls, v: Any) -> Any:
"""set geometry from geo interface or input"""
if isinstance(v, str):
return json.loads(v)
else:
return v


class TableSettings(BaseSettings):
Expand Down

0 comments on commit 1d01330

Please sign in to comment.