style:use restful api

This commit is contained in:
2026-06-20 12:44:32 +08:00
parent f38814e9bd
commit b785178f37
4 changed files with 248 additions and 47 deletions
+78
View File
@@ -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]
+103 -31
View File
@@ -6,12 +6,20 @@ from fastapi import FastAPI, HTTPException, Query
from app.database import (
close_pool,
get_history_by_station,
get_history_by_station_paginated,
get_latest_by_station,
get_station_exists,
init_db,
insert_weather_data,
list_all_stations,
)
from app.models import (
ObservationListResponse,
StationInfo,
StationListResponse,
WeatherDataIn,
WeatherRecordOut,
)
from app.models import WeatherDataIn, WeatherHistoryResponse, WeatherRecordOut
@asynccontextmanager
@@ -25,77 +33,141 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
app = FastAPI(
title="Weather Data API",
description="Receive and query weather station observations",
version="0.1.0",
version="0.2.0",
lifespan=lifespan,
)
@app.post("/data", response_model=WeatherRecordOut, status_code=201)
async def post_weather_data(payload: WeatherDataIn) -> WeatherRecordOut:
"""Ingest a weather observation from a station.
# ---------------------------------------------------------------------------
# Stations
# ---------------------------------------------------------------------------
The server records the time it was received (`received_at`).
"""
record = await insert_weather_data(
station_name=payload.station_name,
temperature=payload.temperature,
pressure=payload.pressure,
relative_humidity=payload.relative_humidity,
@app.get("/stations", response_model=StationListResponse)
async def list_stations() -> StationListResponse:
"""List all known weather stations derived from observation data."""
stations = await list_all_stations()
return StationListResponse(
stations=[StationInfo(**s) for s in stations],
count=len(stations),
)
return WeatherRecordOut(**record)
@app.get("/data/{station_name}", response_model=WeatherRecordOut)
async def get_latest_weather(station_name: str) -> WeatherRecordOut:
"""Return the most recent observation for the given station."""
# ---------------------------------------------------------------------------
# Observations
# ---------------------------------------------------------------------------
@app.get(
"/stations/{station_name}/observations/latest",
response_model=WeatherRecordOut,
)
async def get_latest_observation(station_name: str) -> WeatherRecordOut:
"""Return the most recent observation for a station.
Returns 404 if the station has no observations.
"""
record = await get_latest_by_station(station_name)
if record is None:
raise HTTPException(
status_code=404,
detail=f"No data found for station '{station_name}'",
detail=f"No observations found for station '{station_name}'",
)
return WeatherRecordOut(**record)
@app.get("/data/{station_name}/history", response_model=WeatherHistoryResponse)
async def get_weather_history(
@app.get(
"/stations/{station_name}/observations",
response_model=ObservationListResponse,
)
async def list_observations(
station_name: str,
hours: int | None = Query(
None,
gt=0,
description="Look back this many hours from now (e.g. 24 = last 24 hours). "
"Ignored if both start and end are provided.",
"Overrides start if both are provided.",
),
start: datetime | None = Query(
None,
description="Start of the time range (ISO 8601, UTC). Defaults to unbounded.",
description="Start of the time range (ISO 8601, UTC, inclusive). "
"Defaults to unbounded.",
),
end: datetime | None = Query(
None,
description="End of the time range (ISO 8601, UTC). Defaults to now.",
description="End of the time range (ISO 8601, UTC, inclusive). "
"Defaults to now.",
),
) -> WeatherHistoryResponse:
"""Return all observations for a station within a time range.
limit: int | None = Query(
None,
gt=0,
description="Maximum number of records to return.",
),
offset: int = Query(
0,
ge=0,
description="Number of records to skip (for pagination).",
),
) -> ObservationListResponse:
"""List observations for a station with optional time-range filtering and pagination.
- Use ``hours`` alone to get the last *N* hours of data.
- Use ``start`` and/or ``end`` for a custom range.
- Returns an empty ``records`` list when no data matches.
- Use ``limit`` and ``offset`` for pagination.
- Returns 404 if the station has no observations at all.
- Returns 200 with an empty ``records`` list when no data matches the filters.
"""
if not await get_station_exists(station_name):
raise HTTPException(
status_code=404,
detail=f"Station '{station_name}' not found",
)
now = datetime.now(timezone.utc)
# Resolve start / end from the query parameters
resolved_start: datetime | None = start
resolved_end: datetime | None = end
if hours is not None:
# hours takes precedence for start, but explicit end still wins
resolved_start = now - timedelta(hours=hours)
if end is None:
resolved_end = now
# Default end to now if neither hours nor end was given and start was specified
if resolved_start is not None and resolved_end is None:
resolved_end = now
records = await get_history_by_station(station_name, resolved_start, resolved_end)
return WeatherHistoryResponse(station_name=station_name, records=records)
records = await get_history_by_station_paginated(
station_name,
resolved_start,
resolved_end,
limit=limit,
offset=offset,
)
return ObservationListResponse(
station_name=station_name,
count=len(records),
records=[WeatherRecordOut(**r) for r in records],
)
@app.post(
"/stations/{station_name}/observations",
response_model=WeatherRecordOut,
status_code=201,
)
async def create_observation(
station_name: str,
payload: WeatherDataIn,
) -> WeatherRecordOut:
"""Ingest a weather observation for a station.
The station is identified by the URL path. Stations are created
implicitly when their first observation is posted.
"""
record = await insert_weather_data(
station_name=station_name,
temperature=payload.temperature,
pressure=payload.pressure,
relative_humidity=payload.relative_humidity,
)
return WeatherRecordOut(**record)
+23 -5
View File
@@ -4,9 +4,11 @@ from pydantic import BaseModel, Field
class WeatherDataIn(BaseModel):
"""Payload accepted by POST /data."""
"""Payload accepted by POST /stations/{station_name}/observations.
station_name is taken from the URL path, not the request body.
"""
station_name: str = Field(..., description="Name of the weather station")
temperature: float | None = Field(None, description="Temperature in Celsius")
pressure: float | None = Field(None, description="Atmospheric pressure in hPa")
relative_humidity: float | None = Field(
@@ -15,7 +17,7 @@ class WeatherDataIn(BaseModel):
class WeatherRecordOut(BaseModel):
"""Record returned by the API (includes server-assigned fields)."""
"""A single observation record (includes server-assigned fields)."""
id: int
station_name: str
@@ -25,8 +27,24 @@ class WeatherRecordOut(BaseModel):
received_at: datetime
class WeatherHistoryResponse(BaseModel):
"""Wrapper for history queries — always returns a list (empty if no data)."""
class ObservationListResponse(BaseModel):
"""Response for GET /stations/{station_name}/observations."""
station_name: str
count: int
records: list[WeatherRecordOut]
class StationInfo(BaseModel):
"""Summary of a known weather station."""
name: str
observation_count: int
latest_observation_at: datetime | None
class StationListResponse(BaseModel):
"""Response for GET /stations."""
stations: list[StationInfo]
count: int