-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
334 lines (278 loc) · 12.4 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# ----------------------------------------------------------------------------#
# Imports
# ----------------------------------------------------------------------------#
from flask import Flask, render_template, jsonify, request
from models import db_session, Opportunity,Building, Accounts, Sites, BuildingSchema2, BuildingSchema, AccountSchema,\
AccountSchema2, SitesSchema, CPQSchema, OpportunitySchema, ServiceSchema
import csv
import os
from re import sub
from decimal import Decimal
import sys
import json
# ----------------------------------------------------------------------------#
# App Config.
# ----------------------------------------------------------------------------#
app = Flask(__name__)
app.config.from_object('config')
# Automatically tear down SQLAlchemy.
@app.teardown_request
def shutdown_session(exception=None):
db_session.remove()
# ----------------------------------------------------------------------------#
# Controllers.
# ----------------------------------------------------------------------------#
def calculate_cpq_profit(r_list):
d_profit = 0
for r in r_list:
d_profit += reduce((lambda x, y: x + y.x36_npv_list), r.cpqs, 0)
return d_profit
@app.route('/building_profits/<market>')
def building_profits(market):
result = Building().query.filter(Building.market == market) \
.filter(Building.on_zayo_network_status == "Not on Zayo Network") \
.all()
bs = BuildingSchema2()
building_profits_json = []
for r in result:
try:
cpqs_building = r.cpqs
b_json = bs.dump(r).data
b_json[u'profit'] = 0
for c in cpqs_building:
if r.building_id in b_json:
b_json['profit'] += c.x36_npv_list
else:
b_json['profit'] = c.x36_npv_list
acc_set = set()
for s in r.sites:
acc_set.add(s.account_id)
b_json['accounts'] = list(acc_set)
building_profits_json.append(b_json)
except Exception as e:
print "Unexpected Exception occurred while building profits json"+ str(e)
return jsonify(result=building_profits_json)
@app.route('/account_profits/<market>')
def account_profits(market):
result = Accounts().query.join(Sites, Accounts.account_id == Sites.account_id).join(Building, Building.building_id == Sites.building_id).filter(Building.market == market).filter(Building.on_zayo_network_status == 'Not on Zayo Network').all()
acs = AccountSchema2()
accounts_profits_json = []
for account in result:
try:
acc_json = acs.dump(account).data
acc_json[u'profit'] = 0
acc_json[u'building_list'] = {}
for site in account.sites:
acc_json['building_list'][site.building.building_id] = str(site.building.latitude)+","+str(site.building.longitude)
if len(site.building.cpqs) > 0:
for cpq in site.building.cpqs:
if cpq.account_id in acc_json:
acc_json['profit'] += cpq.x36_npv_list
else:
acc_json['profit'] = cpq.x36_npv_list
accounts_profits_json.append(acc_json)
except:
print "Unexpected Exception occurred while building Accounts json"
return jsonify(result=accounts_profits_json)
@app.route('/market_profits')
def market_profits():
markets = ['Denver', 'Atlanta', 'Dallas']
profits_json = {}
for m in markets:
p = request.cookies.get(m, None)
if p is None:
result = Building().query.filter(Building.market == m) \
.filter(Building.on_zayo_network_status == "Not on Zayo Network").all()
profits_json[m] = calculate_cpq_profit(result)
else:
profits_json[m] = float(p)
resp = jsonify(profits_json)
for m in markets:
resp.set_cookie(m, str(profits_json[m]))
return resp
@app.route('/opportunities/', methods=['POST'])
def opportunities():
req_data = json.loads(request.data)
opps1 = Opportunity().query.filter(Opportunity.account_id.in_(req_data)).all()
opps2 = Opportunity().query.filter(Opportunity.building_id.in_(req_data)).all()
os = OpportunitySchema()
return jsonify(result=os.dump(opps1 + opps2, many=True).data)
@app.route('/initialize')
def initialize():
initialize_buildings()
initialize_accounts()
initialize_sites()
initialize_cpq()
initialize_opportunity()
initialize_services()
return render_template('pages/placeholder.home.html')
def initialize_buildings():
bs = BuildingSchema()
base_dir = os.path.dirname(os.path.realpath(__file__))
with open(base_dir + os.path.sep + 'static' + os.path.sep + 'data' + os.path.sep + 'ZayoHackathonData_Buildings.csv', 'rU') as building_file:
reader = csv.DictReader(building_file, ['building_id', 'market', 'street_address',
'city', 'state', 'postal_code', 'longitude',
'latitude', 'on_zayo_network_status',
'net_classification', 'type', 'network_proximity',
'estimated_build_cost'])
next(reader)
for l in reader:
l["estimated_build_cost"] = Decimal(sub(r'[^\d.]', '', l["estimated_build_cost"]))
try:
b = bs.load(l, session=db_session, partial=True).data
db_session.add(b)
except:
print "a data format exception occurred"
l["postal_code"] = sub(r'[^\x00-\x7F]+', '', l["postal_code"])
print l
if not l["network_proximity"]:
l["network_proximity"] = 0
if not l["latitude"]:
l["latitude"] = 0
if not l["longitude"]:
l["longitude"] = 0
b = bs.load(l, session=db_session, partial=True).data
db_session.add(b)
db_session.commit()
def initialize_accounts():
acs = AccountSchema()
base_dir = os.path.dirname(os.path.realpath(__file__))
with open(base_dir + os.path.sep + 'static' + os.path.sep + 'data' + os.path.sep + 'ZayoHackathonData_Accounts.csv', 'rU') as account_file:
reader = csv.DictReader(account_file, ['account_id', 'industry', 'vertical', 'total_brr', 'annual_revenue',
'number_of_employees', 'dandb_revenue', 'dandb_total_employees'])
next(reader)
for l in reader:
l["total_brr"] = Decimal(sub(r'[^\d.]', '', l["total_brr"]))
l["annual_revenue"] = Decimal(sub(r'[^\d.]', '', l["annual_revenue"]))
l["dandb_revenue"] = Decimal(sub(r'[^\d.]', '', l["dandb_revenue"]))
try:
b = acs.load(l, session=db_session, partial=True).data
db_session.add(b)
except:
print "a data format exception occurred"
print l
db_session.commit()
def initialize_sites():
ss = SitesSchema()
base_dir = os.path.dirname(os.path.realpath(__file__))
with open(base_dir + os.path.sep + 'static' + os.path.sep + 'data' + os.path.sep + 'ZayoHackathonData_Sites.csv', 'rU') as site_file:
reader = csv.DictReader(site_file, ['site_id', 'account_id', 'building_id'])
next(reader)
for l in reader:
del l[None]
try:
b = ss.load(l, session=db_session, partial=True).data
b.account_id = l['account_id']
b.building_id = l['building_id']
db_session.add(b)
except:
print "a data format exception occurred"
print l
db_session.commit()
def initialize_cpq():
cs = CPQSchema()
base_dir = os.path.dirname(os.path.realpath(__file__))
with open(base_dir + os.path.sep + 'static' + os.path.sep + 'data' + os.path.sep + 'ZayoHackathonData_CPQs.csv', 'rU') as cpq_file:
reader = csv.DictReader(cpq_file, ['cpq_id', 'account_id', 'created_date', 'product_group', 'x36_mrc_list',
'x36_nrr_list', 'x36_npv_list', 'building_id'])
next(reader)
for l in reader:
if len(Accounts().query.filter(Accounts.account_id == l['account_id']).all()) == 0:
continue
del l[None]
l['x36_mrc_list'] = Decimal(sub(r'[^\d.]', '', l['x36_mrc_list']))
l['x36_nrr_list'] = Decimal(sub(r'[^\d.]', '', l['x36_nrr_list']))
l['x36_npv_list'] = Decimal(sub(r'[^\d.]', '', l['x36_npv_list']))
try:
b = cs.load(l, session=db_session, partial=True).data
b.account_id = l['account_id']
b.building_id = l['building_id']
db_session.add(b)
except:
print "a data format exception occurred"
print l
db_session.commit()
def initialize_opportunity():
ops = OpportunitySchema()
base_dir = os.path.dirname(os.path.realpath(__file__))
with open(base_dir + os.path.sep + 'static' + os.path.sep + 'data' + os.path.sep + 'ZayoHackathonData_Opportunities.csv',
'rU') as opportunity_file:
reader = csv.DictReader(opportunity_file, ['opportunity_id', 'account_id', 'stage_name', 'is_closed',
'is_won', 'created_date', 'terms_in_month', 'service',
'opportunity_type', 'product_group', 'building_id'])
next(reader)
for l in reader:
del l[None]
if not l['terms_in_month']:
l['terms_in_month'] = 0
try:
b = ops.load(l, session=db_session, partial=True).data
if len(Accounts().query.filter(Accounts.account_id == l['account_id']).all()) == 0:
continue
b.account_id = l['account_id']
b.building_id = l['building_id']
db_session.add(b)
except:
print "a data format exception occurred"
print l
db_session.commit()
def initialize_services():
ss = ServiceSchema()
base_dir = os.path.dirname(os.path.realpath(__file__))
with open(base_dir + os.path.sep + 'static' + os.path.sep + 'data' + os.path.sep + 'ZayoHackathonData_Services.csv', 'rU') as services_file:
reader = csv.DictReader(services_file, ['service_id', 'account_id', 'total_mrr', 'netx_mrc',
'product_group', 'status', 'building_id'])
next(reader)
for l in reader:
if not l['building_id'] or len(
Building().query.filter(Building.building_id == l['building_id']).all()) == 0:
continue
del l[None]
l['total_mrr'] = Decimal(sub(r'[^\d.]', '', l['total_mrr']))
l['netx_mrc'] = Decimal(sub(r'[^\d.]', '', l['netx_mrc']))
try:
b = ss.load(l, session=db_session).data
b.account_id = l['account_id']
b.building_id = l['building_id']
db_session.add(b)
except:
print "a data format exception occurred"
print l
db_session.commit()
@app.route('/')
def home():
return render_template('pages/placeholder.home.html')
@app.route('/about')
def about():
return render_template('pages/placeholder.about.html')
# Error handlers.
@app.errorhandler(500)
def internal_error(error):
db_session.rollback()
return render_template('errors/500.html'), 500
@app.errorhandler(404)
def not_found_error(error):
return render_template('errors/404.html'), 404
"""
if not app.debug:
file_handler = FileHandler('error.log')
file_handler.setFormatter(
Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
)
app.logger.setLevel(logging.INFO)
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.info('errors')
"""
# ----------------------------------------------------------------------------#
# Launch.
# ----------------------------------------------------------------------------#
# Default port:
if __name__ == '__main__':
app.run()
# Or specify port manually:
'''
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
'''