-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
87 lines (64 loc) · 2.6 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
86
87
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request, render_template
import database
import handle_csv
import data_fetch
import datetime
def create_app():
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/all")
def request_all_countries():
""" get information about all countries """
update_data()
year_start = int(request.args.get("start", 0) or 0)
year_end = int(request.args.get("end", 0) or 0)
per_capita = bool(request.args.get("percapita", None))
data = database.get_all_countries_data(year_start, year_end, per_capita)
data_by_code = {}
for code, year, value in data:
if code not in data_by_code:
data_by_code[code] = []
data_by_code[code].append((year, value))
return jsonify(data_by_code)
@app.route("/api/country/<country_code>")
def request_one_country(country_code):
""" get information about a single country """
update_data()
year_start = int(request.args.get("start", 0) or 0)
year_end = int(request.args.get("end", 0) or 0)
per_capita = bool(request.args.get("percapita", None))
data = database.get_one_country_data(
country_code, year_start, year_end, per_capita
)
data_by_code = {data[0][0]: []}
for code, year, value in data:
data_by_code[code].append((year, value))
return jsonify(data_by_code)
@app.route("/api/meta/all")
def request_country_metadata():
""" get metadata of all countries """
update_data()
metadata = database.get_countries_info()
response_data = {
code: {"name": name, "region": region, "income": income, "notes": notes}
for name, code, region, income, notes in metadata
}
return jsonify(response_data)
database.initialize_database()
update_data(force=True)
return app
def update_data(force=False):
""" checks to see if data needs updating, and update if so
currently updates daily, could maybe be less frequent """
last_update_str, = database.get_database_updated() # returns a 1-tuple, unpack it
last_update = datetime.date.fromisoformat(last_update_str)
if last_update < datetime.date.today() or force:
popfile, co2file, countryfile = data_fetch.get_dataset_files()
new_data = handle_csv.load_data(popfile, co2file, countryfile)
popfile.close()
co2file.close()
countryfile.close()
database.update_database(new_data)