-
Notifications
You must be signed in to change notification settings - Fork 28
/
app.py
46 lines (31 loc) · 1.24 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
import requests
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///weather.db'
db = SQLAlchemy(app)
class City(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
new_city = request.form.get('city')
if new_city:
new_city_obj = City(name=new_city)
db.session.add(new_city_obj)
db.session.commit()
cities = City.query.all()
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=271d1234d3f497eed5b1d80a07b3fcd1'
weather_data = []
for city in cities:
r = requests.get(url.format(city.name)).json()
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)