-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
147 lines (115 loc) · 4.92 KB
/
main.py
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import requests
from flask import Flask, request, jsonify
class WeatherTempo:
def __init__(self, api_key):
self.base_url = 'https://api.weatherapi.com/v1/current.json'
self.forecast_url = 'https://api.weatherapi.com/v1/forecast.json'
self.api_key = api_key
def get_current_weather(self, city, units='metric'):
"""
Get the current weather for a specific city.
Parameters:
- city (str): The name of the city for which to retrieve the weather.
- units (str): Optional. The units of measurement for temperature, humidity, and wind speed.
Default is 'metric' (Celsius).
Returns:
- JSON response containing the current weather information, including temperature, humidity,
wind speed, and conditions.
Example usage:
GET /weather?city=London&units=metric
"""
params = {
'key': self.api_key,
'q': city,
'units': units
}
try:
response = requests.get(self.base_url, params=params)
data = response.json()
if 'current' in data:
current = data['current']
temperature = current['temp_c']
humidity = current['humidity']
wind_speed = current['wind_kph']
if units == 'imperial':
temperature = current['temp_f']
humidity = current['humidity']
wind_speed = current['wind_mph']
weather_data = {
'city': city,
'conditions': current['condition']['text'],
'temperature': temperature,
'humidity': humidity,
'wind_speed': wind_speed,
'units': units
}
return jsonify(weather_data)
else:
return jsonify({'error': 'Weather data not available.'})
except requests.exceptions.RequestException as e:
return jsonify({'error': str(e)})
def get_weather_forecast(self, city, days=1, units='metric'):
"""
Get the weather forecast for a specific city for the next few days.
Parameters:
- city (str): The name of the city for which to retrieve the forecast.
- days (int): Optional. The number of days to include in the forecast. Default is 1.
- units (str): Optional. The units of measurement for temperature, humidity, and wind speed.
Default is 'metric' (Celsius).
Returns:
- JSON response containing the weather forecast data for the specified city and days.
Example usage:
GET /forecast?city=London&days=3&units=metric
"""
params = {
'key': self.api_key,
'q': city,
'days': days,
'units': units
}
try:
response = requests.get(self.forecast_url, params=params)
data = response.json()
if 'forecast' in data:
forecast_data = []
for day in data['forecast']['forecastday']:
day_data = day['day']
temperature = day_data['avgtemp_c']
humidity = day_data['avghumidity']
wind_speed = day_data['maxwind_kph']
if units == 'imperial':
temperature = day_data['avgtemp_f']
humidity = day_data['avghumidity']
wind_speed = day_data['maxwind_mph']
forecast_data.append({
'date': day['date'],
'conditions': day_data['condition']['text'],
'temperature': temperature,
'humidity': humidity,
'wind_speed': wind_speed,
'units': units
})
return jsonify(forecast_data)
else:
return jsonify({'error': 'Weather data not available.'})
except requests.exceptions.RequestException as e:
return jsonify({'error': str(e)})
app = Flask(__name__)
weather_app = WeatherTempo(api_key='<YOUR_API_KEY>')
@app.route('/weather', methods=['GET'])
def get_weather():
city = request.args.get('city')
if not city:
return jsonify({'error': 'City parameter is missing.'})
units = request.args.get('units', 'metric')
return weather_app.get_current_weather(city, units)
@app.route('/forecast', methods=['GET'])
def get_forecast():
city = request.args.get('city')
if not city:
return jsonify({'error': 'City parameter is missing.'})
units = request.args.get('units', 'metric')
days = int(request.args.get('days', 1))
return weather_app.get_weather_forecast(city, days, units)
if __name__ == '__main__':
app.run()