[英]How do I formulate my for-loop code to insert values in specific html table cells?
[英]How can I access API data (Python, Requests) in specific cells of my HTML table?
我已經搜索了數小時的stackoverflow,但仍然找不到答案,因此,非常感謝您的幫助! 我正在使用API構建指標儀表板,並且卡住了...
我正在使用請求Python HTTP庫來幫助我從API檢索銷售數據。 這很好用:
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)
以JSON輸出(以1天為例):
{
"2013-03-06": {
"downloads": 1000,
"updates": 20,
"net_downloads": 100,
"revenue": "20.00",
"date": "2013-03-06"
},....
我使用HTML創建了儀表板的結構:
<tr class="dailytarget">
<td class="metricname">Revenue</td>
<td>NEED TO PUT REVENUE TOTAL HERE</td>
</tr>
現在,大問題:如何將表單元分配給JSON輸出中的值? 例如,我需要匯總JSON輸出中的所有“收入”字段,並將它們存儲在表的單元格中。 我怎樣才能做到這一點?
您可以通過遍歷每個json日期信息來匯總所有json數據
如果您的api調用返回一個對象數組:
from decimal import Decimal
total_revenue = sum(Decimal(x['revenue']) for x in data)
這將獲取每個收入值,將其從字符串轉換為Decimal
類型,然后將所有這些值求和。
現在,最基本的就是將total_revenue插入html字符串中
html_str = """
<tr class="dailytarget">
<td class="metricname">Revenue</td>
<td>{}</td>
</tr>""".format(total_revenue)
以上所有操作都是使用format
將總收入值放入字符串中。
現在最棘手的部分是,您將如何向用戶展示此HTML? 如果您想將其公開為網站,則使用任何數量的python Web框架可能是最簡單的
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.