2025-04-01 07:06:10 +00:00
|
|
|
import os
|
|
|
|
import time
|
|
|
|
import logging
|
2025-04-01 00:03:23 +00:00
|
|
|
import requests
|
|
|
|
from django.shortcuts import render
|
|
|
|
|
2025-04-01 07:06:10 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2025-04-01 00:03:23 +00:00
|
|
|
API_KEY = 'a7cc162fc60a76d2e31461071634b8ce'
|
|
|
|
|
2025-04-01 07:06:10 +00:00
|
|
|
def get_weather_data(city):
|
|
|
|
url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric&lang=en'
|
|
|
|
logger.info(f"[weather_request] city={city}")
|
|
|
|
response = requests.get(url)
|
|
|
|
response.raise_for_status()
|
|
|
|
data = response.json()
|
|
|
|
logger.debug(f"[weather_response] city={city} response={data}")
|
|
|
|
return {
|
|
|
|
'city': city,
|
|
|
|
'temperature': data['main']['temp'],
|
|
|
|
'description': data['weather'][0]['description'],
|
|
|
|
'icon': data['weather'][0]['icon'],
|
|
|
|
}
|
|
|
|
|
2025-04-01 00:03:23 +00:00
|
|
|
def index(request):
|
|
|
|
weather_data = None
|
|
|
|
error = None
|
|
|
|
|
2025-04-01 07:06:10 +00:00
|
|
|
if request.method == "POST":
|
|
|
|
city = request.POST.get("city")
|
|
|
|
start = time.time()
|
|
|
|
|
|
|
|
try:
|
|
|
|
weather_data = get_weather_data(city)
|
|
|
|
duration = time.time() - start
|
|
|
|
logger.info(f"[weather_success] city={city} duration={duration:.3f}s temp={weather_data['temperature']}")
|
|
|
|
|
|
|
|
except requests.HTTPError as http_err:
|
|
|
|
error = f"HTTP error: {http_err}"
|
|
|
|
logger.warning(f"[weather_http_error] city={city} error={http_err}")
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
error = "Something went wrong."
|
|
|
|
logger.exception(f"[weather_unexpected_error] city={city} error={e}")
|
|
|
|
|
|
|
|
return render(request, 'weather/index.html', {
|
|
|
|
'weather': weather_data,
|
|
|
|
'error': error,
|
|
|
|
})
|