I've searched stackoverflow for hours and still can't find an answer so I would greatly appreciate your help! I'm building a metrics dashboard using an API and am stuck...
I'm using the requests Python HTTP library to help me retrieve sales data from an API. This is working great:
payload = {'data_source': 'daily'}
r = requests.get('https://api.appfigures.com/v1.1/sales/dates/2013-03-06/2013-03-14', params=payload, auth=(api_key1, api_pass1))
data = json.loads(r.content)
Output in JSON (1 day example):
{
"2013-03-06": {
"downloads": 1000,
"updates": 20,
"net_downloads": 100,
"revenue": "20.00",
"date": "2013-03-06"
},....
I created the structure of the dashboard using HTML:
<tr class="dailytarget">
<td class="metricname">Revenue</td>
<td>NEED TO PUT REVENUE TOTAL HERE</td>
</tr>
Now, the BIG QUESTION: how do I assign the table cells to values in the JSON output? For example, I need to sum up all of the "revenue" fields in the JSON output and store them in a cell in my table. How can I do this?
You can sum up all the json data by iterating through each of your json date information
If your api call is returning an array of objects:
from decimal import Decimal
total_revenue = sum(Decimal(x['revenue']) for x in data)
this takes every revenue value, converts it from a string to a Decimal
type and then sums up all of those values.
Now at the very base all you have to do is insert the total_revenue into your html string
html_str = """
<tr class="dailytarget">
<td class="metricname">Revenue</td>
<td>{}</td>
</tr>""".format(total_revenue)
all the above does is use format
to put the total revenue value into a string.
The tricky part now is, how are you going to present this HTML to a user? If you want to expose it as a website, it might be easiest to use any number of python web frameworks
days = json.loads(r.content)
total_revenue = 0.0
html = "<table>"
html += "<tr><th>Date</th><th>Revenue</th></tr>"
for day in days:
day_revenue = float(day.get('revenue', 0))
html += "<tr><td>%s</td><td>%f</td></tr>" % (day, day_revenue)
total_revenue += day_revenue
html += '<tr><td colspan="2" style="text-align:right;">Total Revenue: %f</td><tr>' % (total_revenue)
html += "</table>"
print html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.