Initial commit
This commit is contained in:
123
main.py
Normal file
123
main.py
Normal file
@ -0,0 +1,123 @@
|
||||
from fastapi import FastAPI, Depends, Query, Request
|
||||
from fastapi.templating import Jinja2Templates
|
||||
import httpx
|
||||
from sqlalchemy.future import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from db import get_session, engine, Base
|
||||
from models import WeatherRecord
|
||||
from datetime import datetime
|
||||
|
||||
app = FastAPI()
|
||||
templates = Jinja2Templates(directory="templates")
|
||||
|
||||
CITIES = {
|
||||
"warszawa": (52.23, 21.01),
|
||||
"krakow": (50.06, 19.94),
|
||||
"gdansk": (54.35, 18.65),
|
||||
}
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
@app.get("/weather")
|
||||
async def get_weather(city: str = Query("warszawa"), session: AsyncSession = Depends(get_session)):
|
||||
coords = CITIES.get(city.lower())
|
||||
if not coords:
|
||||
return {"error": "Miasto nieobsługiwane"}
|
||||
|
||||
url = f"https://api.open-meteo.com/v1/forecast?latitude={coords[0]}&longitude={coords[1]}¤t_weather=true"
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
res = await client.get(url)
|
||||
data = res.json()
|
||||
|
||||
current = data.get("current_weather", {})
|
||||
record = WeatherRecord(
|
||||
city=city.capitalize(),
|
||||
temperature=current.get("temperature"),
|
||||
windspeed=current.get("windspeed"),
|
||||
time=datetime.fromisoformat(current.get("time")),
|
||||
)
|
||||
session.add(record)
|
||||
await session.commit()
|
||||
|
||||
return {
|
||||
"city": record.city,
|
||||
"temperature": record.temperature,
|
||||
"windspeed": record.windspeed,
|
||||
"time": record.time
|
||||
}
|
||||
|
||||
@app.get("/history")
|
||||
async def get_history(city: str = Query("warszawa"), session: AsyncSession = Depends(get_session)):
|
||||
stmt = select(WeatherRecord).where(WeatherRecord.city.ilike(city)).order_by(WeatherRecord.time.desc()).limit(10)
|
||||
result = await session.execute(stmt)
|
||||
records = result.scalars().all()
|
||||
return [
|
||||
{
|
||||
"city": r.city,
|
||||
"temperature": r.temperature,
|
||||
"windspeed": r.windspeed,
|
||||
"time": r.time.isoformat()
|
||||
}
|
||||
for r in records
|
||||
]
|
||||
|
||||
@app.get("/view")
|
||||
async def view_history(request: Request, city: str = "warszawa", session: AsyncSession = Depends(get_session)):
|
||||
stmt = select(WeatherRecord).where(WeatherRecord.city.ilike(city)).order_by(WeatherRecord.time.desc()).limit(10)
|
||||
result = await session.execute(stmt)
|
||||
records = result.scalars().all()
|
||||
return templates.TemplateResponse("history.html", {
|
||||
"request": request,
|
||||
"city": city.capitalize(),
|
||||
"records": records
|
||||
})
|
||||
|
||||
|
||||
@app.get("/ping")
|
||||
async def ping():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/weather/geo")
|
||||
async def get_weather_by_coords(
|
||||
latitude: float = Query(..., ge=-90, le=90),
|
||||
longitude: float = Query(..., ge=-180, le=180),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
url = (
|
||||
f"https://api.open-meteo.com/v1/forecast?"
|
||||
f"latitude={latitude}&longitude={longitude}¤t_weather=true"
|
||||
)
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
res = await client.get(url, timeout=10.0)
|
||||
res.raise_for_status()
|
||||
data = res.json()
|
||||
except httpx.RequestError as e:
|
||||
raise HTTPException(status_code=502, detail=f"Błąd połączenia: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise HTTPException(status_code=502, detail=f"Błąd API pogodowego: {e}")
|
||||
|
||||
current = data.get("current_weather", {})
|
||||
record = WeatherRecord(
|
||||
city="Custom Location",
|
||||
temperature=current.get("temperature"),
|
||||
windspeed=current.get("windspeed"),
|
||||
time=datetime.fromisoformat(current.get("time")),
|
||||
)
|
||||
session.add(record)
|
||||
await session.commit()
|
||||
|
||||
return {
|
||||
"city": record.city,
|
||||
"latitude": latitude,
|
||||
"longitude": longitude,
|
||||
"temperature": record.temperature,
|
||||
"windspeed": record.windspeed,
|
||||
"time": record.time
|
||||
}
|
Reference in New Issue
Block a user