-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
56 lines (42 loc) · 1.83 KB
/
app.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
from flask import Flask, render_template, request
from datetime import datetime
import requests
app = Flask(__name__)
app.config['SECRET_KEY'] = '1234'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/get_weather', methods=['POST'])
def get_weather():
city = request.form.get('city')
api_key = 'f1f994fcdeda4d401f29d4b433c3d16a'
if not city:
return 'Please enter a city.'
try:
location_url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'
location_response = requests.get(location_url)
location_data = location_response.json()
if location_response.status_code == 200:
latitude = location_data['coord']['lat']
longitude = location_data['coord']['lon']
weather_url = f'http://api.openweathermap.org/data/2.5/weather?lat={latitude}&lon={longitude}&appid={api_key}&units=metric'
weather_response = requests.get(weather_url)
weather_data = weather_response.json()
if weather_response.status_code == 200:
temperature = weather_data['main']['temp']
weather_text = weather_data['weather'][0]['description']
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
result = f"City: {city}<br>"
result += f"Latitude: {latitude}<br>"
result += f"Longitude: {longitude}<br>"
result += f"Current Time: {current_time}<br>"
result += f"Weather Forecast: {temperature}°C, {weather_text}"
return result
else:
return 'Error fetching weather data.'
else:
return 'City not found.'
except Exception as e:
return f'Error: {str(e)}'
if __name__ == '__main__':
app.run(debug=True)