-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
204 lines (153 loc) · 5.67 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 13 22:39:29 2022
@author: alyabolowich
"""
import psycopg2
import psycopg2.extras
from flask import request, jsonify, Flask, render_template
from markupsafe import escape
from flask_caching import Cache
import config
#import config
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
cache = Cache(config={'CACHE_TYPE': 'simple'})
cache.init_app(app)
#%%
@app.errorhandler(Exception)
def response(status, data=None, message="OK"):
return jsonify({"status": status, "result": data, "message": message})
#Error handler from pallets projects Flask documentation: https://flask.palletsprojects.com/en/1.1.x/patterns/errorpages/
@app.errorhandler(404)
def resource_404(e):
return jsonify({"status": 404, "result": None, "message": "Not found. The URL is not valid, please verify the URL is correct."})
@app.errorhandler(500)
def resource_500(e):
return jsonify({"status": 500, "result": None, "message": e})
#%% Singleton to create connection
class Connection:
__instance = None
def __init__(self):
self.cur = self.get_con()
def __new__(cls):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
def get_con(self):
con = psycopg2.connect(#database="bsp5", user="postgres", password="5555", host="localhost")
database = config.db_connection["database"],
user = config.db_connection["user"],
password = config.db_connection["password"],
host = config.db_connection["host"])
cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
return cur
#%%
@app.route('/')
def index():
return"My page"
#%%
@app.route('/v1', methods=['GET'])
def home():
return render_template("index.html")
#%%
# Show all sectors
@app.route('/v1/sectors')
def allsectors():
try:
con = Connection()
con.cur.execute('SELECT * from sectors;')
except Exception as e:
return resource_500(str(e))
record = con.cur.fetchall()
record = [dict(row) for row in record]
return response(200, record)
#%%
# Show all regions
@app.route('/v1/regions')
def allregions():
try:
con = Connection()
con.cur.execute('SELECT * from regions;')
except Exception as e:
return resource_500(str(e))
record = con.cur.fetchall()
record = [dict(row) for row in record]
return response(200, record)
#%%
# Get DCBA data
@app.route('/v1/<lens>/<region>')
def dcba(lens, region):
if lens == "consumption":
query = 'SELECT * FROM "{}_dcba" WHERE'.format(escape(region))
elif lens == "production":
query = 'SELECT * FROM "{}_dpba" WHERE'.format(escape(region))
year = request.args.get('year', type=int)
stressor = request.args.get('stressor', "").lower()
sector = request.args.get('sector', "").lower()
#query = 'SELECT * FROM "{}_dcba" WHERE'.format(escape(region))
to_filter = []
region = region.lower()
if not region:
return response(400, message="Bad request - Looks like you need to provide a stressor. Please check you have provided the correect two-letter code.")
if year:
query += ' year=%s AND'
to_filter.append(year)
if stressor:
query += ' stressor=%s AND'
to_filter.append(stressor)
if sector:
query += ' sector=%s AND'
to_filter.append(sector)
if not (year or stressor or sector):
return response(400, message="Bad request - Please check that you have at least provided a year(s), sector(s), or stressor(s).")
query = query[:-4] + 'LIMIT 10;'
try:
con = Connection()
con.cur.execute(query, to_filter)
except Exception as e:
return resource_500(str(e))
record = con.cur.fetchall()
record = [dict(row) for row in record]
if not record:
return response(400, message="Bad request - Please check that your query is correctly entered.")
return response(200, record)
#%%
# Get DPBA data
@app.route('/v1/production/<region>')
def dpba(region):
year = request.args.get('year', type=int)
stressor = request.args.get('stressor', "").lower()
sector = request.args.get('sector', "").lower()
query = 'SELECT * FROM "{}_dpba" WHERE'.format(escape(region))
to_filter = []
region = region.lower()
if not region:
return response(400, message="Bad request - Looks like you need to provide a stressor. Please check you have provided the correect two-letter code.")
if year:
query += ' year=%s AND'
to_filter.append(year)
if stressor:
query += ' stressor=%s AND'
to_filter.append(stressor)
if sector:
query += ' sector=%s AND'
to_filter.append(sector)
if not (year or stressor or sector):
return response(400, message="Bad request - Please check that you have at least provided a year(s), sector(s), or stressor(s).")
query = query[:-4] + ';'
try:
con = Connection()
con.cur.execute(query, to_filter)
except Exception as e:
return resource_500(str(e))
record = con.cur.fetchall()
record = [dict(row) for row in record]
if not record:
return response(400, message="Bad request - Please check that your query is correctly entered.")
return response(200, record)
#%% Run file
if __name__ == "__main__":
app.run(debug=True)