Skip to content

Commit a86140f

Browse files
committed
adapter pattern is created
1 parent 1c7e4ae commit a86140f

File tree

5 files changed

+33
-85
lines changed

5 files changed

+33
-85
lines changed

app/data/__init__.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""app.data"""
2+
from app.services.location import LocationService
23
from ..services.location.csbs import CSBSLocationService
34
from ..services.location.jhu import JhuLocationService
45
from ..services.location.nyt import NYTLocationService
@@ -12,10 +13,4 @@
1213

1314

1415
def data_source(source):
15-
"""
16-
Retrieves the provided data-source service.
17-
18-
:returns: The service.
19-
:rtype: LocationService
20-
"""
21-
return DATA_SOURCES.get(source.lower())
16+
return LocationService(DATA_SOURCES.get(source.lower()))

app/services/location/__init__.py

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,14 @@
11
"""app.services.location"""
2-
from abc import ABC, abstractmethod
32

43

5-
class LocationService(ABC):
6-
"""
7-
Service for retrieving locations.
8-
"""
4+
class LocationService:
95

10-
@abstractmethod
11-
async def get_all(self):
12-
"""
13-
Gets and returns all of the locations.
14-
15-
:returns: The locations.
16-
:rtype: List[Location]
17-
"""
18-
raise NotImplementedError
6+
def __init__(self, resource):
7+
self.resource = resource
198

20-
@abstractmethod
21-
async def get(self, id): # pylint: disable=redefined-builtin,invalid-name
22-
"""
23-
Gets and returns location with the provided id.
9+
async def get_all(self):
10+
return await self.resource.get_locations()
2411

25-
:returns: The location.
26-
:rtype: Location
27-
"""
28-
raise NotImplementedError
12+
async def get(self, id):
13+
locations = await self.get_all()
14+
return locations[id]

app/services/location/csbs.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,11 @@
1515
LOGGER = logging.getLogger("services.location.csbs")
1616

1717

18-
class CSBSLocationService(LocationService):
18+
class CSBSLocationService:
1919
"""
2020
Service for retrieving locations from csbs
2121
"""
2222

23-
async def get_all(self):
24-
# Get the locations.
25-
locations = await get_locations()
26-
return locations
27-
28-
async def get(self, loc_id): # pylint: disable=arguments-differ
29-
# Get location at the index equal to the provided id.
30-
locations = await self.get_all()
31-
return locations[loc_id]
32-
3323

3424
# Base URL for fetching data
3525
BASE_URL = "https://facts.csbs.org/covid-19/covid19_county.csv"
@@ -84,7 +74,8 @@ async def get_locations():
8474
# Coordinates.
8575
Coordinates(item["Latitude"], item["Longitude"]),
8676
# Last update (parse as ISO).
87-
datetime.strptime(last_update, "%Y-%m-%d %H:%M").isoformat() + "Z",
77+
datetime.strptime(
78+
last_update, "%Y-%m-%d %H:%M").isoformat() + "Z",
8879
# Statistics.
8980
int(item["Confirmed"] or 0),
9081
int(item["Death"] or 0),

app/services/location/jhu.py

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -21,27 +21,12 @@
2121
PID = os.getpid()
2222

2323

24-
class JhuLocationService(LocationService):
24+
class JhuLocationService:
2525
"""
2626
Service for retrieving locations from Johns Hopkins CSSE (https://github.com/CSSEGISandData/COVID-19).
2727
"""
28-
29-
async def get_all(self):
30-
# Get the locations.
31-
locations = await get_locations()
32-
return locations
33-
34-
async def get(self, loc_id): # pylint: disable=arguments-differ
35-
# Get location at the index equal to provided id.
36-
locations = await self.get_all()
37-
return locations[loc_id]
38-
39-
40-
# ---------------------------------------------------------------
41-
42-
43-
# Base URL for fetching category.
44-
BASE_URL = "https://raw.githubusercontent.com/CSSEGISandData/2019-nCoV/master/csse_covid_19_data/csse_covid_19_time_series/"
28+
# Base URL for fetching category.
29+
BASE_URL = "https://raw.githubusercontent.com/CSSEGISandData/2019-nCoV/master/csse_covid_19_data/csse_covid_19_time_series/"
4530

4631

4732
@cached(cache=TTLCache(maxsize=4, ttl=1800))
@@ -82,10 +67,12 @@ async def get_category(category):
8267

8368
for item in data:
8469
# Filter out all the dates.
85-
dates = dict(filter(lambda element: date_util.is_date(element[0]), item.items()))
70+
dates = dict(
71+
filter(lambda element: date_util.is_date(element[0]), item.items()))
8672

8773
# Make location history from dates.
88-
history = {date: int(float(amount or 0)) for date, amount in dates.items()}
74+
history = {date: int(float(amount or 0))
75+
for date, amount in dates.items()}
8976

9077
# Country for this location.
9178
country = item["Country/Region"]
@@ -101,7 +88,7 @@ async def get_category(category):
10188
"country_code": countries.country_code(country),
10289
"province": item["Province/State"],
10390
# Coordinates.
104-
"coordinates": {"lat": item["Lat"], "long": item["Long"],},
91+
"coordinates": {"lat": item["Lat"], "long": item["Long"], },
10592
# History.
10693
"history": history,
10794
# Latest statistic.
@@ -178,7 +165,8 @@ async def get_locations():
178165
location["country"],
179166
location["province"],
180167
# Coordinates.
181-
Coordinates(latitude=coordinates["lat"], longitude=coordinates["long"]),
168+
Coordinates(
169+
latitude=coordinates["lat"], longitude=coordinates["long"]),
182170
# Last update.
183171
datetime.utcnow().isoformat() + "Z",
184172
# Timelines (parse dates as ISO).

app/services/location/nyt.py

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -16,27 +16,12 @@
1616
LOGGER = logging.getLogger("services.location.nyt")
1717

1818

19-
class NYTLocationService(LocationService):
19+
class NYTLocationService:
2020
"""
21-
Service for retrieving locations from New York Times (https://github.com/nytimes/covid-19-data).
21+
Service for retrieving locations from Johns Hopkins CSSE (https://github.com/CSSEGISandData/COVID-19).
2222
"""
23-
24-
async def get_all(self):
25-
# Get the locations.
26-
locations = await get_locations()
27-
return locations
28-
29-
async def get(self, loc_id): # pylint: disable=arguments-differ
30-
# Get location at the index equal to provided id.
31-
locations = await self.get_all()
32-
return locations[loc_id]
33-
34-
35-
# ---------------------------------------------------------------
36-
37-
38-
# Base URL for fetching category.
39-
BASE_URL = "https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv"
23+
# Base URL for fetching category.
24+
BASE_URL = "https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv"
4025

4126

4227
def get_grouped_locations_dict(data):
@@ -104,18 +89,21 @@ async def get_locations():
10489
# Make location history for confirmed and deaths from dates.
10590
# List is tuples of (date, amount) in order of increasing dates.
10691
confirmed_list = histories["confirmed"]
107-
confirmed_history = {date: int(amount or 0) for date, amount in confirmed_list}
92+
confirmed_history = {date: int(amount or 0)
93+
for date, amount in confirmed_list}
10894

10995
deaths_list = histories["deaths"]
110-
deaths_history = {date: int(amount or 0) for date, amount in deaths_list}
96+
deaths_history = {date: int(amount or 0)
97+
for date, amount in deaths_list}
11198

11299
# Normalize the item and append to locations.
113100
locations.append(
114101
NYTLocation(
115102
id=idx,
116103
state=county_state[1],
117104
county=county_state[0],
118-
coordinates=Coordinates(None, None), # NYT does not provide coordinates
105+
# NYT does not provide coordinates
106+
coordinates=Coordinates(None, None),
119107
last_updated=datetime.utcnow().isoformat() + "Z", # since last request
120108
timelines={
121109
"confirmed": Timeline(

0 commit comments

Comments
 (0)