Files
weather-fetch-lab/exporter.py
T
2026-09-28 17:10:20 +03:00

66 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import datetime
from collections.abc import Sequence
from pathlib import Path
from db_models import WeatherForecast
_HEADERS = [
"Дата",
"Мин. темп. (°C)",
"Макс. темп. (°C)",
"Описание",
"Влажность (%)",
"Ветер (м/с)",
]
def _format_number(value: float) -> str:
return f"{value:g}"
def export_md(records: Sequence[WeatherForecast], output_file: str, city: str) -> None:
rows: list[list[str]] = []
for record in sorted(records, key=lambda r: r.forecast_date):
rows.append(
[
record.forecast_date.isoformat(),
_format_number(record.temp_min),
_format_number(record.temp_max),
record.description or "",
str(record.humidity),
_format_number(record.wind_speed),
]
)
if records:
dates: list[datetime.date] = [r.forecast_date for r in records]
period = f"Период: {min(dates).isoformat()} - {max(dates).isoformat()}"
else:
period = "Период: -"
location = f"Автоматически определённая локация: {city}"
widths = [len(header) for header in _HEADERS]
for row in rows:
for i, cell in enumerate(row):
widths[i] = max(widths[i], len(cell))
def _row(row: list[str]) -> str:
padded = [cell.ljust(widths[i]) for i, cell in enumerate(row)]
return "| " + " | ".join(padded) + " |"
separator = "| " + " | ".join("-" * width for width in widths) + " |"
lines = [
"# Прогноз погоды",
"",
location,
period,
"",
_row(_HEADERS),
separator,
*(_row(row) for row in rows),
"",
]
Path(output_file).write_text("\n".join(lines), encoding="utf-8")