Skip to content

Commit f35fec1

Browse files
[MRG+1] Avoid KeyError on downloads badge script (#318)
1 parent 99b39a6 commit f35fec1

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

etc/downloads_badges.py

+30-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import math
44
import os
55
import requests
6+
from statistics import mean
67

78

89
def millify(n):
@@ -42,6 +43,25 @@ def millify(n):
4243
return f'{final_output}{millnames[millidx]}'
4344

4445

46+
def get_default_value(downloads):
47+
"""Find the default value (one day's worth of downloads) for a given input
48+
49+
Parameters
50+
----------
51+
downloads : dict
52+
A dict of dates and downloads on that day
53+
54+
Returns
55+
-------
56+
default_value : int
57+
The default value, which is the average of the last 7 days of downloads
58+
that are contained in the input dictionary.
59+
"""
60+
last_7_keys = sorted(downloads.keys())[-7:]
61+
default_value = int(mean([downloads[key] for key in last_7_keys]))
62+
return default_value
63+
64+
4565
# Used to calculate downloads for the last week
4666
today = date.today()
4767
last_week = today - timedelta(days=7)
@@ -56,12 +76,20 @@ def millify(n):
5676

5777
# Sum up pmdarima and pyramid-arima downloads to the past week
5878
pmdarima_downloads = 0
79+
default_pmdarima_value = get_default_value(pmdarima['downloads'])
5980
for i in range(7):
60-
pmdarima_downloads += pmdarima['downloads'][(last_week + timedelta(days=i)).strftime(DATE_FORMAT)]
81+
pmdarima_downloads += pmdarima['downloads'].get(
82+
(last_week + timedelta(days=i)).strftime(DATE_FORMAT),
83+
default_pmdarima_value
84+
)
6185

6286
pyramid_arima_downloads = 0
87+
default_pyramid_arima_value = get_default_value(pyramid_arima['downloads'])
6388
for i in range(7):
64-
pyramid_arima_downloads += pyramid_arima['downloads'][(last_week + timedelta(days=i)).strftime(DATE_FORMAT)]
89+
pyramid_arima_downloads += pyramid_arima['downloads'].get(
90+
(last_week + timedelta(days=i)).strftime(DATE_FORMAT),
91+
default_pyramid_arima_value
92+
)
6593

6694
# Millify the totals
6795
total_downloads = millify(pyramid_arima['total_downloads'] + pmdarima['total_downloads'])

0 commit comments

Comments
 (0)