This repository has been archived by the owner on Apr 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
stratPlanDownload.py
176 lines (146 loc) · 4.61 KB
/
stratPlanDownload.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
###
# This script downloads agency strategic plans and saves them to the database.
###
import sqlite3
import requests
import string
import re
import time
import sys
# Our JSON might not be... pristine, so we must use a more flexible module.
from barely_json import parse
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# Stop yelling about the insecure requests.
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
import config
# Request headers for our scraper.
headers = {
'User-Agent': 'OFCIO DCOI Scraper',
'From': '[email protected]'
}
conn = sqlite3.connect(config.DB_CONFIG['file'])
c = conn.cursor()
fileLocation = "/digitalstrategy/datacenteroptimizationstrategicplan.json"
agencies = {
"Commerce": "https://www.commerce.gov",
"DHS": "http://www.dhs.gov",
"DOD": "http://www.defense.gov",
"DOT": "https://www.transportation.gov",
"ED": "https://www2.ed.gov",
"Energy": "http://www.energy.gov",
"EPA": "http://www.epa.gov",
"GSA": "http://www.gsa.gov",
"HHS": "http://www.hhs.gov",
"HUD": "http://www.hud.gov",
"Interior": "https://www.doi.gov",
"Justice": "https://www.justice.gov",
"Labor": "http://www.dol.gov",
"NASA": "http://www.nasa.gov",
"NRC": "https://www.nrc.gov",
"NSF": "https://www.nsf.gov",
"OPM": "http://www.opm.gov",
"SBA": "http://www.sba.gov",
"SSA": "http://www.ssa.gov",
"State": "http://www.state.gov",
"Treasury": "http://www.treasury.gov",
"USAID": "http://www.usaid.gov",
"USDA": "http://www.usda.gov",
"VA": "http://www.va.gov"
}
missingAgencies = []
today = int(time.strftime("%Y%m%d"))
types = [
'costSavings',
'closures',
('optimizationMetrics', 'energyMetering'),
('optimizationMetrics', 'virtualization'),
('optimizationMetrics', 'underutilizedServers'),
('optimizationMetrics', 'availability')
]
fields = [
'fy16Planned',
'fy16Achieved',
'fy17Planned',
'fy17Achieved',
'fy18Planned',
'fy18Achieved',
'fy19Planned',
'fy19Achieved',
'fy20Planned',
'fy20Achieved',
'explanation',
'methodology',
'costsOfClosures',
'costsOfOptimization',
'historicalCostSavings'
]
def filter_nonprintable(text):
nonprintable = set([chr(i) for i in range(128)]).difference(string.printable)
return re.sub(r'[^\x00-\x7f]',r'',
text.translate({ord(character):None for character in nonprintable})
)
for agency in agencies:
planFile = agencies[agency] + fileLocation
print(agency, planFile)
try:
# Give at least ten seconds for slower agencies to respond
# Don't verify the certificate since agencies stuggle with SSL.
r = requests.get(planFile, timeout=10, headers=headers, verify=False)
except:
print('! Cannot download file. {}'.format(sys.exc_info()[0]))
missingAgencies.append(agency)
continue
if r.status_code == 200 and len(r.text):
text = filter_nonprintable(r.text)
try:
data = parse(text)
except:
print('! Error in file.', sys.exc_info()[0])
missingAgencies.append(agency)
continue
if not 'closures' in data:
print('! Using old schema.')
missingAgencies.append(agency)
continue
# Delete any previous plans.
conn.execute('DELETE FROM stratplans WHERE agency=:agency', {'agency': agency})
# Insert into database.
# loop over our categories.
for type in types:
if isinstance(type, str):
if type in data:
row = data[type]
elif isinstance(type, tuple):
(key, type) = type
if key in data and type in data[key]:
row = data[key][type]
else:
print('Missing JSON field "{}"'.format(type))
continue
# Holder for our data to put into the database.
insertData = {
'agency': agency,
'importDate': today,
'type': type
}
# Then loop over our fields and build the insert data.
for field in fields:
if field in row:
# We store these floats as strings due to Python's precision.
# https://github.com/ombegov/dcoi/issues/6
insertData[field] = str(row[field])
# Create a string for the insert statement.
insertString = 'INSERT INTO stratplans ({}) VALUES({})'.format(
', '.join(insertData.keys()), # fields list
', '.join([':'+key for key in insertData.keys()]) # values: fill with ":fieldName"
)
conn.execute(insertString, insertData)
else:
print('! Cannot download file. (HTTP {})'.format(r.status_code))
missingAgencies.append(agency)
continue
# Commit and close the connection.
conn.commit()
conn.close()
if len(missingAgencies):
print('Could not download these strategic plans:', missingAgencies)