import os from datetime import datetime import requests from flask import Flask, jsonify, render_template_string, request app = Flask(__name__) # Get API key from environment variable (preferred) or use demo key API_KEY = os.getenv("API_KEY", "6cf356ceb2ec0ff941855d4a43144e0e") BASE_URL = "https://api.openweathermap.org/data/2.5/weather" # HTML Template with embedded CSS and JavaScript - MUST BE DEFINED BEFORE ROUTES HTML_TEMPLATE = """ Weather Forecast

Weather Forecast

Get real-time weather information for any city worldwide

Fetching weather data...

-

-
Weather Icon

-

Feels Like
-
Humidity
-
Pressure
-
Wind Speed
-
Visibility
-
Sunrise / Sunset
-
""" def get_weather(city): """Fetch weather data from OpenWeatherMap API""" try: url = f"{BASE_URL}?q={city}&appid={API_KEY}&units=metric" response = requests.get(url, timeout=10) response.raise_for_status() # Raises an HTTPError for bad responses data = response.json() main = data["main"] weather = data["weather"][0] sys = data.get("sys", {}) return { "city": data["name"], "country": sys.get("country", ""), "temperature": round(main["temp"]), "feels_like": round(main["feels_like"]), "description": weather["description"].title(), "humidity": main["humidity"], "pressure": main["pressure"], "wind_speed": round(data["wind"]["speed"], 1), "wind_deg": data["wind"].get("deg", 0), "visibility": data.get("visibility", 0), "icon": weather["icon"], "sunrise": datetime.fromtimestamp(sys.get("sunrise", 0)).strftime("%H:%M") if sys.get("sunrise") else "N/A", "sunset": datetime.fromtimestamp(sys.get("sunset", 0)).strftime("%H:%M") if sys.get("sunset") else "N/A", "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), } except requests.exceptions.RequestException as e: print(f"API request failed: {e}") return None except (KeyError, ValueError) as e: print(f"Error parsing weather data: {e}") return None @app.route("/") def home(): return render_template_string(HTML_TEMPLATE) @app.route("/weather", methods=["GET", "POST"]) def weather(): if request.method == "POST": city = request.form.get("city") else: city = request.args.get("city") if not city: return jsonify({"error": "City parameter is required"}), 400 weather_data = get_weather(city) if weather_data: return jsonify(weather_data) else: return jsonify({"error": "City not found or API request failed"}), 404 @app.route("/health") def health(): return jsonify({"status": "healthy", "timestamp": datetime.now().isoformat()}) if __name__ == "__main__": app.run(host="0.0.0.0", port=5000, debug=False)