-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
85 lines (67 loc) · 2.42 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
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
# install required libraries:,
# pip install Flask
# pip install Flask-SQLAlchemy
import requests
import string
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__,template_folder='template')
app.config['DEBUG'] = True
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=metric&appid=b21c4b237a9ce5e59e747cfbe70c2e26"
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)
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')
new_city = new_city.lower()
new_city = string.capwords(new_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 = 'That isnt a valid city!'
else:
err_msg = 'City already exists !' #already existing in a database
if err_msg:
flash(err_msg, 'error')
else:
flash('City added successfully!', 'success')
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,port=8000)