-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwebReporter.py
64 lines (56 loc) · 2.34 KB
/
webReporter.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
#!/usr/bin/env python3
#
# Simple SparkPost Traffic Generator
#
# Web reporting and access functions for shared data held in Redis
#
import os, redis, json
from flask import Flask, make_response, render_template, request, send_file
app = Flask(__name__)
# Access to Redis data
def getResults():
redisUrl = os.getenv('REDIS_URL', default='redis://localhost:6379') # Env var is set by Heroku; will be unset when local
r = redis.from_url(redisUrl, socket_timeout=5) # shorten timeout so doesn't hang forever
rkey = 'sparkpost-traffic-gen:' + os.getenv('RESULTS_KEY', default='0000')
res = r.get(rkey)
if res:
return json.loads(res)
else:
return {}
# returns True if data written back to Redis OK
def setResults(res):
redisUrl = os.getenv('REDIS_URL', default='redis://localhost:6379') # Env var is set by Heroku; will be unset when local
r = redis.from_url(redisUrl, socket_timeout=5) # shorten timeout so doesn't hang forever
rkey = 'sparkpost-traffic-gen:' + os.getenv('RESULTS_KEY', default='0000')
return r.set(rkey, res)
# read config from env vars, where present
def getConfig():
return {
'sparkpost_host': os.getenv('SPARKPOST_HOST', 'https://api.sparkpost.com'),
'messages_per_minute_low': os.getenv('MESSAGES_PER_MINUTE_LOW'),
'messages_per_minute_high': os.getenv('MESSAGES_PER_MINUTE_HIGH'),
'from_email': os.getenv('FROM_EMAIL')
}
# Flask entry points
@app.route('/', methods=['GET'])
def status_html():
r = getResults()
if not r: # empty results - show helpful message
r['startedRunning'] = 'Not yet - waiting for scheduled running to begin'
r.update(getConfig())
# pass in merged dict as named params to template substitutions
return render_template('index.html', **r, jsonUrl=request.url+'json')
# This entry point returns JSON-format report on the traffic generator
@app.route('/json', methods=['GET'])
def status_json():
r = getResults()
r.update(getConfig())
flaskRes = make_response(json.dumps(r))
flaskRes.headers['Content-Type'] = 'application/json'
return flaskRes
@app.route('/favicon.ico')
def favicon():
return send_file('favicon.ico', mimetype='image/vnd.microsoft.icon')
# Start the app
if __name__ == "__main__":
app.run()