forked from ExpDev07/coronavirus-tracker-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
73 lines (57 loc) · 2.08 KB
/
__init__.py
File metadata and controls
73 lines (57 loc) · 2.08 KB
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
import requests
import csv
from datetime import datetime
from cachetools import cached, TTLCache
from ..utils import countrycodes, date as date_util
"""
Base URL for fetching data.
"""
base_url = 'https://raw.githubusercontent.com/CSSEGISandData/2019-nCoV/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-%s.csv';
@cached(cache=TTLCache(maxsize=1024, ttl=3600))
def get_data(category):
"""
Retrieves the data for the provided type. The data is cached for 1 hour.
"""
# Adhere to category naming standard.
category = category.lower().capitalize();
# Request the data
request = requests.get(base_url % category)
text = request.text
# Parse the CSV.
data = list(csv.DictReader(text.splitlines()))
# The normalized locations.
locations = []
for item in data:
# Filter out all the dates.
dates = dict(filter(lambda element: date_util.is_date(element[0]), item.items()))
# Make location history from dates.
history = { date: int(amount or 0) for date, amount in dates.items() };
# Country for this location.
country = item['Country/Region']
# Latest data insert value.
latest = list(history.values())[-1];
# Normalize the item and append to locations.
locations.append({
# General info.
'country': country,
'country_code': countrycodes.country_code(country),
'province': item['Province/State'],
# Coordinates.
'coordinates': {
'lat': item['Lat'],
'long': item['Long'],
},
# History.
'history': history,
# Latest statistic.
'latest': int(latest or 0),
})
# Latest total.
latest = sum(map(lambda location: location['latest'], locations))
# Return the final data.
return {
'locations': locations,
'latest': latest,
'last_updated': datetime.utcnow().isoformat() + 'Z',
'source': 'https://github.com/ExpDev07/coronavirus-tracker-api',
}