style:use restful api
This commit is contained in:
@@ -123,3 +123,81 @@ async def get_history_by_station(
|
||||
*params,
|
||||
)
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
async def list_all_stations() -> list[dict]:
|
||||
"""Return all distinct station names with observation counts and latest timestamps.
|
||||
|
||||
Derives stations from weather_data since there is no separate stations table.
|
||||
"""
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
rows = await conn.fetch("""
|
||||
SELECT
|
||||
station_name AS name,
|
||||
COUNT(*)::int AS observation_count,
|
||||
MAX(received_at) AS latest_observation_at
|
||||
FROM weather_data
|
||||
GROUP BY station_name
|
||||
ORDER BY station_name
|
||||
""")
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
async def get_station_exists(station_name: str) -> bool:
|
||||
"""Check whether a station has any observations."""
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"SELECT 1 FROM weather_data WHERE station_name = $1 LIMIT 1",
|
||||
station_name,
|
||||
)
|
||||
return row is not None
|
||||
|
||||
|
||||
async def get_history_by_station_paginated(
|
||||
station_name: str,
|
||||
start_time: datetime | None = None,
|
||||
end_time: datetime | None = None,
|
||||
limit: int | None = None,
|
||||
offset: int = 0,
|
||||
) -> list[dict]:
|
||||
"""Return observations for a station within the given time range, with pagination.
|
||||
|
||||
Returns an empty list if no records match.
|
||||
"""
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
conditions = ["station_name = $1"]
|
||||
params: list = [station_name]
|
||||
idx = 2
|
||||
|
||||
if start_time is not None:
|
||||
conditions.append(f"received_at >= ${idx}")
|
||||
params.append(start_time)
|
||||
idx += 1
|
||||
|
||||
if end_time is not None:
|
||||
conditions.append(f"received_at <= ${idx}")
|
||||
params.append(end_time)
|
||||
idx += 1
|
||||
|
||||
where_clause = " AND ".join(conditions)
|
||||
|
||||
query = f"""
|
||||
SELECT id, station_name, temperature, pressure, relative_humidity, received_at
|
||||
FROM weather_data
|
||||
WHERE {where_clause}
|
||||
ORDER BY received_at DESC
|
||||
"""
|
||||
|
||||
if limit is not None:
|
||||
query += f" LIMIT ${idx}"
|
||||
params.append(limit)
|
||||
idx += 1
|
||||
|
||||
query += f" OFFSET ${idx}"
|
||||
params.append(offset)
|
||||
|
||||
rows = await conn.fetch(query, *params)
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
Reference in New Issue
Block a user