-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
58 lines (46 loc) · 1.8 KB
/
app.py
File metadata and controls
58 lines (46 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from flask import Flask, render_template, request, jsonify
import requests
import os
from dotenv import load_dotenv
load_dotenv() # Load environment variables from .env
app = Flask(__name__)
# Get API key from environment
API_KEY = os.getenv("WEATHER_API_KEY")
if not API_KEY:
raise RuntimeError("WEATHER_API_KEY not found in environment variables.")
@app.route("/")
def home():
return render_template("index.html")
@app.route("/weather", methods=["GET"])
def get_weather():
lat = request.args.get("lat")
lon = request.args.get("lon")
if not lat or not lon:
return jsonify({"error": "Latitude and Longitude are required"}), 400
try:
url = f"https://api.weatherapi.com/v1/forecast.json?key={API_KEY}&q={lat},{lon}&hours=24"
response = requests.get(url)
data = response.json()
forecast = [
{
"time": hour["time"].split(" ")[1],
"temp": hour["temp_c"],
"condition": hour["condition"]["text"],
"icon": hour["condition"]["icon"]
}
for hour in data["forecast"]["forecastday"][0]["hour"]
]
return jsonify({
"location": f"{data['location']['name']}, {data['location']['country']}",
"temp": data["current"]["temp_c"],
"condition": data["current"]["condition"]["text"],
"icon": data["current"]["condition"]["icon"],
"wind_kph": data["current"]["wind_kph"],
"rain_prob": data["forecast"]["forecastday"][0]["day"].get("daily_chance_of_rain", 0),
"forecast": forecast
})
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host="0.0.0.0", port=port, debug=True)