forked from linkong/planet
685 lines
22 KiB
Python
685 lines
22 KiB
Python
import csv
|
|
import hashlib
|
|
import io
|
|
import json
|
|
from typing import Optional
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
from fastapi.responses import StreamingResponse
|
|
from sqlalchemy import select, text
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.cache import cache
|
|
from app.core.collected_data_fields import get_metadata_field
|
|
from app.core.countries import COUNTRY_OPTIONS, get_country_search_variants, normalize_country
|
|
from app.core.security import get_current_user
|
|
from app.core.time import to_iso8601_utc
|
|
from app.db.session import get_db
|
|
from app.models.datasource import DataSource
|
|
from app.models.user import User
|
|
|
|
router = APIRouter()
|
|
|
|
DEFAULT_EXCLUDED_DATA_TYPES: tuple[str, ...] = ("prefix_geography",)
|
|
DEFAULT_EXCLUDED_SOURCES: frozenset[str] = frozenset(
|
|
{"iptoasn_prefix_geo", "opengeofeed_prefix_geo", "nro_delegated_prefix_geo"}
|
|
)
|
|
COLLECTED_FACETS_CACHE_KEY = "collected:facets:v1"
|
|
COLLECTED_FACETS_TTL_SECONDS = 300
|
|
COLLECTED_SUMMARY_TTL_SECONDS = 60
|
|
|
|
COUNTRY_SQL = "metadata->>'country'"
|
|
SEARCHABLE_SQL = [
|
|
"name",
|
|
"title",
|
|
"description",
|
|
"source",
|
|
"data_type",
|
|
"source_id",
|
|
"metadata::text",
|
|
]
|
|
|
|
|
|
def parse_multi_values(value: Optional[str]) -> list[str]:
|
|
if not value:
|
|
return []
|
|
return [item.strip() for item in value.split(",") if item.strip()]
|
|
|
|
|
|
def build_in_condition(field_sql: str, values: list[str], param_prefix: str, params: dict) -> str:
|
|
placeholders = []
|
|
for index, value in enumerate(values):
|
|
key = f"{param_prefix}_{index}"
|
|
params[key] = value
|
|
placeholders.append(f":{key}")
|
|
return f"{field_sql} IN ({', '.join(placeholders)})"
|
|
|
|
|
|
def build_not_in_condition(field_sql: str, values: tuple[str, ...], param_prefix: str, params: dict) -> str:
|
|
placeholders = []
|
|
for index, value in enumerate(values):
|
|
key = f"{param_prefix}_{index}"
|
|
params[key] = value
|
|
placeholders.append(f":{key}")
|
|
return f"{field_sql} NOT IN ({', '.join(placeholders)})"
|
|
|
|
|
|
def _includes_default_excluded(source_values: list[str], data_type_values: list[str]) -> bool:
|
|
if any(dt in DEFAULT_EXCLUDED_DATA_TYPES for dt in data_type_values):
|
|
return True
|
|
if any(src in DEFAULT_EXCLUDED_SOURCES for src in source_values):
|
|
return True
|
|
return False
|
|
|
|
|
|
def _facets_cache_key(mode: str) -> str:
|
|
return COLLECTED_FACETS_CACHE_KEY if mode != "history" else f"{COLLECTED_FACETS_CACHE_KEY}:history"
|
|
|
|
|
|
def _summary_cache_key(
|
|
*,
|
|
mode: str,
|
|
source: Optional[str],
|
|
data_type: Optional[str],
|
|
country: Optional[str],
|
|
search: Optional[str],
|
|
) -> str:
|
|
payload = json.dumps(
|
|
{
|
|
"mode": "history" if mode == "history" else "current",
|
|
"source": source or "",
|
|
"data_type": data_type or "",
|
|
"country": country or "",
|
|
"search": (search or "").strip(),
|
|
},
|
|
sort_keys=True,
|
|
ensure_ascii=False,
|
|
)
|
|
digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()[:24]
|
|
return f"collected:summary:v1:{digest}"
|
|
|
|
|
|
def build_search_condition(search: Optional[str], params: dict) -> Optional[str]:
|
|
if not search:
|
|
return None
|
|
|
|
normalized = search.strip()
|
|
if not normalized:
|
|
return None
|
|
|
|
search_terms = [normalized]
|
|
for variant in get_country_search_variants(normalized):
|
|
if variant.casefold() not in {term.casefold() for term in search_terms}:
|
|
search_terms.append(variant)
|
|
|
|
conditions = []
|
|
for index, term in enumerate(search_terms):
|
|
params[f"search_{index}"] = f"%{term}%"
|
|
conditions.extend(f"{field} ILIKE :search_{index}" for field in SEARCHABLE_SQL)
|
|
|
|
params["search_exact"] = normalized
|
|
params["search_prefix"] = f"{normalized}%"
|
|
|
|
canonical_variants = get_country_search_variants(normalized)
|
|
canonical = canonical_variants[0] if canonical_variants else None
|
|
params["country_search_exact"] = canonical or normalized
|
|
params["country_search_prefix"] = f"{(canonical or normalized)}%"
|
|
|
|
return "(" + " OR ".join(conditions) + ")"
|
|
|
|
|
|
def build_search_rank_sql(search: Optional[str]) -> str:
|
|
if not search or not search.strip():
|
|
return "0"
|
|
|
|
return """
|
|
CASE
|
|
WHEN name ILIKE :search_exact THEN 700
|
|
WHEN name ILIKE :search_prefix THEN 600
|
|
WHEN title ILIKE :search_exact THEN 500
|
|
WHEN title ILIKE :search_prefix THEN 400
|
|
WHEN metadata->>'country' ILIKE :country_search_exact THEN 380
|
|
WHEN metadata->>'country' ILIKE :country_search_prefix THEN 340
|
|
WHEN source_id ILIKE :search_exact THEN 350
|
|
WHEN source ILIKE :search_exact THEN 300
|
|
WHEN data_type ILIKE :search_exact THEN 250
|
|
WHEN description ILIKE :search_0 THEN 150
|
|
WHEN metadata::text ILIKE :search_0 THEN 100
|
|
WHEN title ILIKE :search_0 THEN 80
|
|
WHEN name ILIKE :search_0 THEN 60
|
|
WHEN source ILIKE :search_0 THEN 40
|
|
WHEN data_type ILIKE :search_0 THEN 30
|
|
WHEN source_id ILIKE :search_0 THEN 20
|
|
ELSE 0
|
|
END
|
|
"""
|
|
|
|
|
|
def serialize_collected_row(
|
|
row,
|
|
source_name_map: dict[str, str] | None = None,
|
|
*,
|
|
include_metadata: bool = True,
|
|
) -> dict:
|
|
raw_metadata = row[7]
|
|
if isinstance(raw_metadata, str):
|
|
try:
|
|
metadata = json.loads(raw_metadata)
|
|
except json.JSONDecodeError:
|
|
metadata = None
|
|
else:
|
|
metadata = raw_metadata
|
|
source = row[1]
|
|
return {
|
|
"id": row[0],
|
|
"source": source,
|
|
"source_name": source_name_map.get(source, source) if source_name_map else source,
|
|
"source_id": row[2],
|
|
"data_type": row[3],
|
|
"name": row[4],
|
|
"title": row[5],
|
|
"description": row[6],
|
|
"country": get_metadata_field(metadata, "country"),
|
|
"city": get_metadata_field(metadata, "city"),
|
|
"latitude": get_metadata_field(metadata, "latitude"),
|
|
"longitude": get_metadata_field(metadata, "longitude"),
|
|
"value": get_metadata_field(metadata, "value"),
|
|
"unit": get_metadata_field(metadata, "unit"),
|
|
"metadata": metadata if include_metadata else None,
|
|
"cores": get_metadata_field(metadata, "cores"),
|
|
"rmax": get_metadata_field(metadata, "rmax"),
|
|
"rpeak": get_metadata_field(metadata, "rpeak"),
|
|
"power": get_metadata_field(metadata, "power"),
|
|
"collected_at": to_iso8601_utc(row[8]),
|
|
"reference_date": to_iso8601_utc(row[9]),
|
|
"is_valid": row[10],
|
|
}
|
|
|
|
|
|
async def get_source_name_map(db: AsyncSession) -> dict[str, str]:
|
|
result = await db.execute(select(DataSource.source, DataSource.name))
|
|
return {row[0]: row[1] for row in result.fetchall()}
|
|
|
|
|
|
async def _load_collected_facets(
|
|
db: AsyncSession,
|
|
*,
|
|
mode: str,
|
|
source_name_map: dict[str, str] | None = None,
|
|
) -> list[dict]:
|
|
cache_key = _facets_cache_key(mode)
|
|
cached_facets = cache.get(cache_key)
|
|
if isinstance(cached_facets, list):
|
|
return cached_facets
|
|
|
|
where_sql = "is_current IS TRUE" if mode != "history" else "1=1"
|
|
result = await db.execute(
|
|
text(
|
|
f"""
|
|
SELECT source, data_type, COUNT(*) AS count
|
|
FROM collected_data
|
|
WHERE {where_sql}
|
|
GROUP BY source, data_type
|
|
ORDER BY source, data_type
|
|
"""
|
|
)
|
|
)
|
|
names = source_name_map if source_name_map is not None else await get_source_name_map(db)
|
|
facets = [
|
|
{
|
|
"source": row[0],
|
|
"source_name": names.get(row[0], row[0]),
|
|
"data_type": row[1],
|
|
"count": int(row[2] or 0),
|
|
}
|
|
for row in result.fetchall()
|
|
]
|
|
cache.set(cache_key, facets, expire_seconds=COLLECTED_FACETS_TTL_SECONDS)
|
|
return facets
|
|
|
|
|
|
@router.get("")
|
|
async def list_collected_data(
|
|
mode: str = Query("current", description="查询模式: current/history"),
|
|
source: Optional[str] = Query(None, description="数据源过滤"),
|
|
data_type: Optional[str] = Query(None, description="数据类型过滤"),
|
|
country: Optional[str] = Query(None, description="国家过滤"),
|
|
search: Optional[str] = Query(None, description="搜索名称"),
|
|
page: int = Query(1, ge=1, description="页码"),
|
|
page_size: int = Query(20, ge=1, le=100, description="每页数量"),
|
|
include_metadata: bool = Query(True, description="是否返回完整 metadata 字段"),
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
"""查询采集的数据列表"""
|
|
where_sql, params, include_excluded = build_where_clause(
|
|
source,
|
|
data_type,
|
|
country,
|
|
search,
|
|
mode=mode,
|
|
)
|
|
has_search = bool(search and search.strip())
|
|
|
|
# Calculate offset
|
|
offset = (page - 1) * page_size
|
|
source_name_map = await get_source_name_map(db)
|
|
|
|
if not country and not has_search:
|
|
facets = await _load_collected_facets(db, mode=mode, source_name_map=source_name_map)
|
|
source_set = set(parse_multi_values(source))
|
|
type_set = set(parse_multi_values(data_type))
|
|
total = sum(
|
|
item["count"]
|
|
for item in facets
|
|
if (include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES)
|
|
and (not source_set or item["source"] in source_set)
|
|
and (not type_set or item["data_type"] in type_set)
|
|
)
|
|
else:
|
|
count_query = text(f"SELECT COUNT(*) FROM collected_data WHERE {where_sql}")
|
|
count_result = await db.execute(count_query, params)
|
|
total = int(count_result.scalar() or 0)
|
|
|
|
params["limit"] = page_size
|
|
params["offset"] = offset
|
|
if has_search:
|
|
search_rank_sql = build_search_rank_sql(search)
|
|
query = text(
|
|
f"""
|
|
SELECT id, source, source_id, data_type, name, title, description,
|
|
metadata, collected_at, reference_date, is_valid,
|
|
{search_rank_sql} AS search_rank
|
|
FROM collected_data
|
|
WHERE {where_sql}
|
|
ORDER BY search_rank DESC, collected_at DESC
|
|
LIMIT :limit OFFSET :offset
|
|
"""
|
|
)
|
|
else:
|
|
query = text(
|
|
f"""
|
|
SELECT id, source, source_id, data_type, name, title, description,
|
|
metadata, collected_at, reference_date, is_valid
|
|
FROM collected_data
|
|
WHERE {where_sql}
|
|
ORDER BY collected_at DESC
|
|
LIMIT :limit OFFSET :offset
|
|
"""
|
|
)
|
|
|
|
result = await db.execute(query, params)
|
|
rows = result.fetchall()
|
|
|
|
data = []
|
|
for row in rows:
|
|
data.append(serialize_collected_row(row[:11], source_name_map, include_metadata=include_metadata))
|
|
|
|
return {
|
|
"total": total,
|
|
"page": page,
|
|
"page_size": page_size,
|
|
"data": data,
|
|
}
|
|
|
|
|
|
def _aggregate_summary_from_facets(facets: list[dict], *, overall_total: int) -> dict:
|
|
by_source: dict[str, dict[str, int]] = {}
|
|
source_acc: dict[str, dict] = {}
|
|
type_acc: dict[str, int] = {}
|
|
total = 0
|
|
|
|
for item in facets:
|
|
src = str(item["source"])
|
|
src_name = str(item.get("source_name") or src)
|
|
dt = str(item["data_type"])
|
|
cnt = int(item["count"] or 0)
|
|
if cnt <= 0:
|
|
continue
|
|
by_source.setdefault(src_name, {})[dt] = by_source.get(src_name, {}).get(dt, 0) + cnt
|
|
if src not in source_acc:
|
|
source_acc[src] = {"source": src, "source_name": src_name, "count": 0}
|
|
source_acc[src]["count"] += cnt
|
|
type_acc[dt] = type_acc.get(dt, 0) + cnt
|
|
total += cnt
|
|
|
|
source_totals = sorted(source_acc.values(), key=lambda x: (-x["count"], x["source"]))
|
|
type_totals = [
|
|
{"data_type": dt, "count": cnt}
|
|
for dt, cnt in sorted(type_acc.items(), key=lambda item: (-item[1], item[0]))
|
|
]
|
|
return {
|
|
"total_records": total,
|
|
"overall_total_records": overall_total,
|
|
"by_source": by_source,
|
|
"source_totals": source_totals,
|
|
"type_totals": type_totals,
|
|
}
|
|
|
|
|
|
@router.get("/summary")
|
|
async def get_data_summary(
|
|
mode: str = Query("current", description="查询模式: current/history"),
|
|
source: Optional[str] = Query(None, description="数据源过滤"),
|
|
data_type: Optional[str] = Query(None, description="数据类型过滤"),
|
|
country: Optional[str] = Query(None, description="国家过滤"),
|
|
search: Optional[str] = Query(None, description="搜索名称"),
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
"""获取数据汇总统计"""
|
|
cache_key = _summary_cache_key(
|
|
mode=mode,
|
|
source=source,
|
|
data_type=data_type,
|
|
country=country,
|
|
search=search,
|
|
)
|
|
cached_summary = cache.get(cache_key)
|
|
if isinstance(cached_summary, dict):
|
|
return cached_summary
|
|
|
|
source_name_map = await get_source_name_map(db)
|
|
unfiltered_facets = await _load_collected_facets(
|
|
db, mode=mode, source_name_map=source_name_map
|
|
)
|
|
source_values = parse_multi_values(source)
|
|
data_type_values = parse_multi_values(data_type)
|
|
include_excluded = _includes_default_excluded(source_values, data_type_values)
|
|
overall_total = sum(
|
|
int(item["count"] or 0)
|
|
for item in unfiltered_facets
|
|
if include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES
|
|
)
|
|
|
|
normalized_country = normalize_country(country) if country else None
|
|
has_search = bool(search and search.strip())
|
|
|
|
if not normalized_country and not has_search:
|
|
source_set = set(source_values)
|
|
type_set = set(data_type_values)
|
|
filtered_facets = [
|
|
item
|
|
for item in unfiltered_facets
|
|
if (include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES)
|
|
and (not source_set or item["source"] in source_set)
|
|
and (not type_set or item["data_type"] in type_set)
|
|
]
|
|
else:
|
|
where_sql, params, _ = build_where_clause(
|
|
source,
|
|
data_type,
|
|
country,
|
|
search,
|
|
mode=mode,
|
|
)
|
|
result = await db.execute(
|
|
text(
|
|
f"""
|
|
SELECT source, data_type, COUNT(*) AS count
|
|
FROM collected_data
|
|
WHERE {where_sql}
|
|
GROUP BY source, data_type
|
|
ORDER BY source, data_type
|
|
"""
|
|
),
|
|
params,
|
|
)
|
|
filtered_facets = [
|
|
{
|
|
"source": row[0],
|
|
"source_name": source_name_map.get(row[0], row[0]),
|
|
"data_type": row[1],
|
|
"count": int(row[2] or 0),
|
|
}
|
|
for row in result.fetchall()
|
|
]
|
|
|
|
payload = _aggregate_summary_from_facets(filtered_facets, overall_total=overall_total)
|
|
cache.set(cache_key, payload, expire_seconds=COLLECTED_SUMMARY_TTL_SECONDS)
|
|
return payload
|
|
|
|
|
|
@router.get("/sources")
|
|
async def get_data_sources(
|
|
mode: str = Query("current", description="查询模式: current/history"),
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
"""获取所有数据源列表"""
|
|
facets = await _load_collected_facets(db, mode=mode)
|
|
seen: dict[str, str] = {}
|
|
for item in facets:
|
|
src = str(item["source"])
|
|
if src not in seen:
|
|
seen[src] = str(item.get("source_name") or src)
|
|
|
|
return {
|
|
"sources": [
|
|
{"source": src, "source_name": seen[src]}
|
|
for src in sorted(seen.keys())
|
|
],
|
|
}
|
|
|
|
|
|
@router.get("/types")
|
|
async def get_data_types(
|
|
mode: str = Query("current", description="查询模式: current/history"),
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
"""获取所有数据类型列表"""
|
|
facets = await _load_collected_facets(db, mode=mode)
|
|
types = sorted({str(item["data_type"]) for item in facets if item.get("data_type")})
|
|
return {
|
|
"data_types": types,
|
|
}
|
|
|
|
|
|
@router.get("/countries")
|
|
async def get_countries(
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
"""获取所有国家列表"""
|
|
|
|
return {
|
|
"countries": COUNTRY_OPTIONS,
|
|
}
|
|
|
|
|
|
@router.get("/{data_id}")
|
|
async def get_collected_data(
|
|
data_id: int,
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
"""获取单条采集数据详情"""
|
|
|
|
result = await db.execute(
|
|
text("""
|
|
SELECT id, source, source_id, data_type, name, title, description,
|
|
metadata, collected_at, reference_date, is_valid
|
|
FROM collected_data
|
|
WHERE id = :id
|
|
"""),
|
|
{"id": data_id},
|
|
)
|
|
row = result.fetchone()
|
|
|
|
if not row:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="数据不存在",
|
|
)
|
|
|
|
source_name_map = await get_source_name_map(db)
|
|
return serialize_collected_row(row, source_name_map)
|
|
|
|
|
|
def build_where_clause(
|
|
source: Optional[str],
|
|
data_type: Optional[str],
|
|
country: Optional[str],
|
|
search: Optional[str],
|
|
*,
|
|
mode: str = "current",
|
|
) -> tuple[str, dict, bool]:
|
|
"""Build WHERE clause and params for queries."""
|
|
conditions = []
|
|
params: dict = {}
|
|
if mode != "history":
|
|
conditions.append("is_current IS TRUE")
|
|
|
|
source_values = parse_multi_values(source)
|
|
data_type_values = parse_multi_values(data_type)
|
|
include_excluded = _includes_default_excluded(source_values, data_type_values)
|
|
|
|
if source_values:
|
|
conditions.append(build_in_condition("source", source_values, "source", params))
|
|
if data_type_values:
|
|
conditions.append(build_in_condition("data_type", data_type_values, "data_type", params))
|
|
if not include_excluded and DEFAULT_EXCLUDED_DATA_TYPES:
|
|
conditions.append(build_not_in_condition("data_type", DEFAULT_EXCLUDED_DATA_TYPES, "excl_dt", params))
|
|
|
|
normalized_country = normalize_country(country) if country else None
|
|
if normalized_country:
|
|
conditions.append(f"{COUNTRY_SQL} = :country")
|
|
params["country"] = normalized_country
|
|
search_condition = build_search_condition(search, params)
|
|
if search_condition:
|
|
conditions.append(search_condition)
|
|
|
|
where_sql = " AND ".join(conditions) if conditions else "1=1"
|
|
return where_sql, params, include_excluded
|
|
|
|
|
|
@router.get("/export/json")
|
|
async def export_json(
|
|
mode: str = Query("current", description="查询模式: current/history"),
|
|
source: Optional[str] = Query(None, description="数据源过滤"),
|
|
data_type: Optional[str] = Query(None, description="数据类型过滤"),
|
|
country: Optional[str] = Query(None, description="国家过滤"),
|
|
search: Optional[str] = Query(None, description="搜索名称"),
|
|
limit: int = Query(10000, ge=1, le=50000, description="最大导出数量"),
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
"""导出数据为 JSON 格式"""
|
|
|
|
where_sql, params, _ = build_where_clause(source, data_type, country, search, mode=mode)
|
|
params["limit"] = limit
|
|
|
|
query = text(f"""
|
|
SELECT id, source, source_id, data_type, name, title, description,
|
|
metadata, collected_at, reference_date, is_valid
|
|
FROM collected_data
|
|
WHERE {where_sql}
|
|
ORDER BY collected_at DESC
|
|
LIMIT :limit
|
|
""")
|
|
|
|
result = await db.execute(query, params)
|
|
rows = result.fetchall()
|
|
|
|
data = []
|
|
for row in rows:
|
|
data.append(serialize_collected_row(row))
|
|
|
|
json_str = json.dumps({"data": data, "total": len(data)}, ensure_ascii=False, indent=2)
|
|
|
|
return StreamingResponse(
|
|
io.StringIO(json_str),
|
|
media_type="application/json",
|
|
headers={
|
|
"Content-Disposition": f"attachment; filename=collected_data_{source or 'all'}.json"
|
|
},
|
|
)
|
|
|
|
|
|
@router.get("/export/csv")
|
|
async def export_csv(
|
|
mode: str = Query("current", description="查询模式: current/history"),
|
|
source: Optional[str] = Query(None, description="数据源过滤"),
|
|
data_type: Optional[str] = Query(None, description="数据类型过滤"),
|
|
country: Optional[str] = Query(None, description="国家过滤"),
|
|
search: Optional[str] = Query(None, description="搜索名称"),
|
|
limit: int = Query(10000, ge=1, le=50000, description="最大导出数量"),
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
"""导出数据为 CSV 格式"""
|
|
|
|
where_sql, params, _ = build_where_clause(source, data_type, country, search, mode=mode)
|
|
params["limit"] = limit
|
|
|
|
query = text(f"""
|
|
SELECT id, source, source_id, data_type, name, title, description,
|
|
metadata, collected_at, reference_date, is_valid
|
|
FROM collected_data
|
|
WHERE {where_sql}
|
|
ORDER BY collected_at DESC
|
|
LIMIT :limit
|
|
""")
|
|
|
|
result = await db.execute(query, params)
|
|
rows = result.fetchall()
|
|
|
|
output = io.StringIO()
|
|
writer = csv.writer(output)
|
|
|
|
# Write header
|
|
writer.writerow(
|
|
[
|
|
"ID",
|
|
"Source",
|
|
"Source ID",
|
|
"Type",
|
|
"Name",
|
|
"Title",
|
|
"Description",
|
|
"Country",
|
|
"City",
|
|
"Latitude",
|
|
"Longitude",
|
|
"Value",
|
|
"Unit",
|
|
"Metadata",
|
|
"Collected At",
|
|
"Reference Date",
|
|
"Is Valid",
|
|
]
|
|
)
|
|
|
|
# Write data
|
|
for row in rows:
|
|
writer.writerow(
|
|
[
|
|
row[0],
|
|
row[1],
|
|
row[2],
|
|
row[3],
|
|
row[4],
|
|
row[5],
|
|
row[6],
|
|
get_metadata_field(row[7], "country"),
|
|
get_metadata_field(row[7], "city"),
|
|
get_metadata_field(row[7], "latitude"),
|
|
get_metadata_field(row[7], "longitude"),
|
|
get_metadata_field(row[7], "value"),
|
|
get_metadata_field(row[7], "unit"),
|
|
json.dumps(row[7]) if row[7] else "",
|
|
to_iso8601_utc(row[8]) or "",
|
|
to_iso8601_utc(row[9]) or "",
|
|
row[10],
|
|
]
|
|
)
|
|
|
|
return StreamingResponse(
|
|
io.StringIO(output.getvalue()),
|
|
media_type="text/csv",
|
|
headers={
|
|
"Content-Disposition": f"attachment; filename=collected_data_{source or 'all'}.csv"
|
|
},
|
|
)
|