-
Notifications
You must be signed in to change notification settings - Fork 0
/
WeatherPredictionApp.py
83 lines (61 loc) · 2.2 KB
/
WeatherPredictionApp.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
import requests
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///weather.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'thisisasecret'
db = SQLAlchemy(app)
class City(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def get_weather_data(city):
url = f'http://api.openweathermap.org/data/2.5/weather?q={ city }&units=imperial&appid=271d1234d3f497eed5b1d80a07b3fcd1'
r = requests.get(url).json()
return r
@app.route('/')
def index_get():
cities = City.query.all()
weather_data = []
for city in cities:
r = get_weather_data(city.name)
##print(r)
weather = {
'city' : city.name,
'temperature' : r['main']['temp'],
'description' : r['weather'][0]['description'],
'icon' : r['weather'][0]['icon'],
}
weather_data.append(weather)
return render_template('weather.html', weather_data=weather_data)
@app.route('/', methods=['POST'])
def index_post():
err_msg = ''
new_city = request.form.get('city')
if new_city:
existing_city = City.query.filter_by(name=new_city).first()
if not existing_city:
new_city_data = get_weather_data(new_city)
if new_city_data['cod'] == 200:
new_city_obj = City(name=new_city)
db.session.add(new_city_obj)
db.session.commit()
else:
err_msg = 'City does not exist in the world!'
else:
err_msg = 'City already exists in the database!'
if err_msg:
flash(err_msg, 'error')
else:
flash('City added succesfully!')
return redirect(url_for('index_get'))
@app.route('/delete/<name>')
def delete_city(name):
city = City.query.filter_by(name=name).first()
db.session.delete(city)
db.session.commit()
flash(f'Successfully deleted { city.name }', 'success')
return redirect(url_for('index_get'))
if __name__ == '__main__':
db.create_all()
app.run(debug = True)