Skip to content

Commit

Permalink
Cleanup helper for flexibility
Browse files Browse the repository at this point in the history
  • Loading branch information
alukach committed Sep 19, 2024
1 parent c337c31 commit d8a2430
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions space2stats_api/src/space2stats/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,29 @@
from psycopg import Connection

from .h3_utils import generate_h3_geometries, generate_h3_ids
from .settings import Settings
from .types import AoiModel

if TYPE_CHECKING:
from .settings import Settings


@dataclass
class StatsTable:
conn: Connection
table_name: str

@classmethod
def from_settings(cls, settings: "Settings") -> "StatsTable":
def connect(cls, settings: Optional[Settings] = None, **kwargs) -> "StatsTable":
"""
Helper method to connect to the database and return a StatsTable instance.
It is left up to the caller to close the connection when finished, eg:
```py
stats_table = StatsTable.connect()
try:
stats_table.summaries(aoi, spatial_join_method, fields)
finally:
stats_table.conn.close()
```
"""
settings = settings or Settings(**kwargs)
conn = pg.connect(settings.DB_CONNECTION_STRING)
return cls(conn=conn, table_name=settings.PGTABLENAME)

Expand Down

0 comments on commit d8a2430

Please sign in to comment.