59 lines
1.8 KiB
Python
59 lines
1.8 KiB
Python
import os
|
|||
|
|
import sys
|
||
|
|
|
||
|
|
from dotenv import load_dotenv
|
||
|
|
from sqlalchemy import create_engine, select
|
||
|
|
from sqlalchemy.exc import SQLAlchemyError
|
||
|
|
from sqlalchemy.orm import Session
|
||
|
|
|
||
|
|
from db_models import Base, WeatherForecast, save_forecasts
|
||
|
|
from exporter import export_md
|
||
|
|
from geo_locator import GeoError, get_geo
|
||
|
|
from weather_client import WeatherAPIError, get_forecast
|
||
|
|
|
||
|
|
|
||
|
|
def main() -> None:
|
||
|
|
load_dotenv()
|
||
|
|
|
||
|
|
try:
|
||
|
|
geo = get_geo()
|
||
|
|
print(
|
||
|
|
f"{geo.city}{'' if geo.lat is None or geo.lon is None else f' ({geo.lat}, {geo.lon})'}"
|
||
|
|
)
|
||
|
|
|
||
|
|
forecasts = get_forecast(geo)
|
||
|
|
print(f"{len(forecasts)} days forecast")
|
||
|
|
|
||
|
|
database_url = os.getenv("DB_URL", "sqlite:///weather.db").format(
|
||
|
|
DB_USER=os.getenv("DB_USER", ""),
|
||
|
|
DB_PASSWORD=os.getenv("DB_PASSWORD", ""),
|
||
|
|
)
|
||
|
|
city = forecasts[0].city
|
||
|
|
engine = create_engine(database_url)
|
||
|
|
Base.metadata.create_all(engine)
|
||
|
|
with Session(engine) as session:
|
||
|
|
saved = save_forecasts(session, forecasts)
|
||
|
|
records = list(
|
||
|
|
session.scalars(
|
||
|
|
select(WeatherForecast)
|
||
|
|
.where(WeatherForecast.city == city)
|
||
|
|
.order_by(WeatherForecast.forecast_date)
|
||
|
|
).all()
|
||
|
|
)
|
||
|
|
print(f"records: {len(records)}{f' +{saved}' if saved > 0 else ''}")
|
||
|
|
|
||
|
|
output_file = os.getenv("OUTPUT_FILE", "weather_report.md")
|
||
|
|
export_md(records, output_file, city)
|
||
|
|
print(f"Exported: {output_file}")
|
||
|
|
|
||
|
|
if records:
|
||
|
|
dates = sorted(r.forecast_date for r in records)
|
||
|
|
print(f"{dates[0]} - {dates[-1]}")
|
||
|
|
except (GeoError, WeatherAPIError, SQLAlchemyError) as exc:
|
||
|
|
print(f"error: {exc}", file=sys.stderr)
|
||
|
|
sys.exit(1)
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
main()
|