django-weather/weather_project/weather/views.py

27 lines
910 B
Python
Raw Normal View History

2025-04-01 00:03:23 +00:00
import requests
from django.shortcuts import render
API_KEY = 'a7cc162fc60a76d2e31461071634b8ce'
def index(request):
weather_data = None
error = None
if request.method == 'POST':
city = request.POST.get('city')
if city:
url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric&lang=eng'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
weather_data = {
'city': city,
'temperature': data['main']['temp'],
'description': data['weather'][0]['description'],
'icon': data['weather'][0]['icon']
}
else:
error = 'City not found'
return render(request, 'weather/index.html', {'weather': weather_data, 'error': error})