refactor(weather): add app_build method

This commit is contained in:
2024-07-28 20:26:38 +03:00
parent 48a6cce569
commit 1fb627110d
12 changed files with 254 additions and 199 deletions

View File

@@ -6,8 +6,10 @@ from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from gismeteo import datehelp
from gismeteo.location import LOCATION_BUNDLE
from gismeteo.mock import MOCK_DATA
from weather.api import get_api
from weather.model import WeatherResponse
from .filters import cloudness_icon, wind_direction_icon
@@ -19,6 +21,30 @@ def mount(app: FastAPI):
templates.env.filters["wind_direction_icon"] = wind_direction_icon
templates.env.filters["cloudness_icon"] = cloudness_icon
def build_weather_response(request: Request, response: WeatherResponse):
return templates.TemplateResponse(
request=request,
name="weather.html",
context={
"datetime": datetime,
"response": response,
},
)
@app.get("/", response_class=RedirectResponse)
async def get_weather_root():
return RedirectResponse("weather")
@app.get("/weather", response_class=HTMLResponse)
async def get_weather_list(request: Request):
return templates.TemplateResponse(
request=request,
name="index.html",
context={
"locations": LOCATION_BUNDLE._values,
},
)
@app.get("/weather/{location}", response_class=RedirectResponse)
async def get_weather_default(location: str):
return RedirectResponse(f"{location}/{datetime.date.today()}")
@@ -26,23 +52,15 @@ def mount(app: FastAPI):
@app.get("/weather/{location}/mock", response_class=HTMLResponse)
async def get_weather_mock(request: Request):
response = MOCK_DATA.response
return templates.TemplateResponse(
request=request,
name="weather.html",
context={
"datetime": datetime,
"response": response,
},
)
return build_weather_response(request, response)
# @app.get("/weather/{location}/{day}", response_class=HTMLResponse)
async def get_weather_day(request: Request, location: str, day: datehelp.Day):
date = datehelp.parse(day)
response = await request.app.state.weather_api.get_day(location, date)
return build_weather_response(request, response)
@app.get("/weather/{location}/{date}", response_class=HTMLResponse)
async def get_weather(request: Request, location: str, date: datetime.date):
response = await get_api().get_day(location, date)
return templates.TemplateResponse(
request=request,
name="weather.html",
context={
"datetime": datetime,
"response": response,
},
)
response = await request.app.state.weather_api.get_day(location, date)
return build_weather_response(request, response)