Skip to content

Commit d2b1bb5

Browse files
author
dengrf96
committed
Apply Creational Design Pattern
1 parent 1c7e4ae commit d2b1bb5

File tree

4 files changed

+100
-80
lines changed

4 files changed

+100
-80
lines changed

app/location/locationfactory.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import datetime
2+
3+
from app.coordinates import Coordinates
4+
from app.location import TimelinedLocation
5+
from app.location.csbs import CSBSLocation
6+
from app.location.nyt import NYTLocation
7+
from app.models import Timeline
8+
9+
10+
class LocationFactory:
11+
def __init__(self):
12+
pass
13+
14+
@staticmethod
15+
def create_location(org_name, params):
16+
if org_name == 'NYT':
17+
confirmed_history = params["confirmed_history"]
18+
deaths_history = params["deaths_history"]
19+
return NYTLocation(
20+
id=params["index"],
21+
state=params["county_state"][1],
22+
county=params["county_state"][0],
23+
coordinates=Coordinates(None, None), # NYT does not provide coordinates
24+
last_updated=datetime.utcnow().isoformat() + "Z", # since last request
25+
timelines={
26+
"confirmed": Timeline(
27+
timeline={
28+
datetime.strptime(date, "%Y-%m-%d").isoformat() + "Z": amount
29+
for date, amount in confirmed_history.items()
30+
}
31+
),
32+
"deaths": Timeline(
33+
timeline={
34+
datetime.strptime(date, "%Y-%m-%d").isoformat() + "Z": amount
35+
for date, amount in deaths_history.items()
36+
}
37+
),
38+
"recovered": Timeline(),
39+
},
40+
)
41+
elif org_name == "JHU":
42+
timelines = params["timelines"];
43+
return TimelinedLocation(
44+
# General info.
45+
params["index"],
46+
params["country"],
47+
params["province"],
48+
# Coordinates.
49+
Coordinates(latitude=params["coordinates"]["lat"], longitude=params["coordinates"]["long"]),
50+
# Last update.
51+
datetime.utcnow().isoformat() + "Z",
52+
# Timelines (parse dates as ISO).
53+
{
54+
"confirmed": Timeline(
55+
timeline={
56+
datetime.strptime(date, "%m/%d/%y").isoformat() + "Z": amount
57+
for date, amount in timelines["confirmed"].items()
58+
}
59+
),
60+
"deaths": Timeline(
61+
timeline={
62+
datetime.strptime(date, "%m/%d/%y").isoformat() + "Z": amount
63+
for date, amount in timelines["deaths"].items()
64+
}
65+
),
66+
"recovered": Timeline(
67+
timeline={
68+
datetime.strptime(date, "%m/%d/%y").isoformat() + "Z": amount
69+
for date, amount in timelines["recovered"].items()
70+
}
71+
),
72+
},
73+
)
74+
elif org_name == "CSBS":
75+
item = params["item"]
76+
return CSBSLocation(
77+
# General info.
78+
params["index"],
79+
params["state"],
80+
params["county"],
81+
# Coordinates.
82+
Coordinates(item["Latitude"], item["Longitude"]),
83+
# Last update (parse as ISO).
84+
datetime.strptime(params["last_update"], "%Y-%m-%d %H:%M").isoformat() + "Z",
85+
# Statistics.
86+
int(item["Confirmed"] or 0),
87+
int(item["Death"] or 0),
88+
)

app/services/location/csbs.py

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from ...caches import check_cache, load_cache
1010
from ...coordinates import Coordinates
11+
from ...location import locationfactory
1112
from ...location.csbs import CSBSLocation
1213
from ...utils import httputils
1314
from . import LocationService
@@ -73,23 +74,9 @@ async def get_locations():
7374

7475
# Date string without "EDT" at end.
7576
last_update = " ".join(item["Last Update"].split(" ")[0:2])
76-
77+
params = {"index": i, "state": state, "county": county, "item": item, "last_update": last_update}
7778
# Append to locations.
78-
locations.append(
79-
CSBSLocation(
80-
# General info.
81-
i,
82-
state,
83-
county,
84-
# Coordinates.
85-
Coordinates(item["Latitude"], item["Longitude"]),
86-
# Last update (parse as ISO).
87-
datetime.strptime(last_update, "%Y-%m-%d %H:%M").isoformat() + "Z",
88-
# Statistics.
89-
int(item["Confirmed"] or 0),
90-
int(item["Death"] or 0),
91-
)
92-
)
79+
locations.append(locationfactory.create_location('CSBS'))
9380
LOGGER.info(f"{data_id} Data normalized")
9481
# save the results to distributed cache
9582
# TODO: fix json serialization

app/services/location/jhu.py

Lines changed: 5 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
from ...caches import check_cache, load_cache
1212
from ...coordinates import Coordinates
13-
from ...location import TimelinedLocation
13+
from ...location import TimelinedLocation, locationfactory
1414
from ...models import Timeline
1515
from ...utils import countries
1616
from ...utils import date as date_util
@@ -171,39 +171,10 @@ async def get_locations():
171171
coordinates = location["coordinates"]
172172

173173
# Create location (supporting timelines) and append.
174-
locations.append(
175-
TimelinedLocation(
176-
# General info.
177-
index,
178-
location["country"],
179-
location["province"],
180-
# Coordinates.
181-
Coordinates(latitude=coordinates["lat"], longitude=coordinates["long"]),
182-
# Last update.
183-
datetime.utcnow().isoformat() + "Z",
184-
# Timelines (parse dates as ISO).
185-
{
186-
"confirmed": Timeline(
187-
timeline={
188-
datetime.strptime(date, "%m/%d/%y").isoformat() + "Z": amount
189-
for date, amount in timelines["confirmed"].items()
190-
}
191-
),
192-
"deaths": Timeline(
193-
timeline={
194-
datetime.strptime(date, "%m/%d/%y").isoformat() + "Z": amount
195-
for date, amount in timelines["deaths"].items()
196-
}
197-
),
198-
"recovered": Timeline(
199-
timeline={
200-
datetime.strptime(date, "%m/%d/%y").isoformat() + "Z": amount
201-
for date, amount in timelines["recovered"].items()
202-
}
203-
),
204-
},
205-
)
206-
)
174+
175+
params= {"index": index, "country": location["country"], "province": location["province"],
176+
"coordinates": coordinates, "timelines": timelines}
177+
locations.append(locationfactory.create_location("JHU"), params)
207178
LOGGER.info(f"{data_id} Data normalized")
208179

209180
# Finally, return the locations.

app/services/location/nyt.py

Lines changed: 4 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
11
"""app.services.location.nyt.py"""
22
import csv
33
import logging
4-
from datetime import datetime
5-
64
from asyncache import cached
75
from cachetools import TTLCache
86

97
from ...caches import check_cache, load_cache
10-
from ...coordinates import Coordinates
11-
from ...location.nyt import NYTLocation
12-
from ...models import Timeline
8+
from ...location import locationfactory
139
from ...utils import httputils
1410
from . import LocationService
1511

@@ -108,32 +104,10 @@ async def get_locations():
108104

109105
deaths_list = histories["deaths"]
110106
deaths_history = {date: int(amount or 0) for date, amount in deaths_list}
107+
params = {'index': idx, 'county_state': county_state, 'confirmed_history': confirmed_history,
108+
'deaths_history': deaths_history}
109+
locations.append(locationfactory.create_location('NYT', params))
111110

112-
# Normalize the item and append to locations.
113-
locations.append(
114-
NYTLocation(
115-
id=idx,
116-
state=county_state[1],
117-
county=county_state[0],
118-
coordinates=Coordinates(None, None), # NYT does not provide coordinates
119-
last_updated=datetime.utcnow().isoformat() + "Z", # since last request
120-
timelines={
121-
"confirmed": Timeline(
122-
timeline={
123-
datetime.strptime(date, "%Y-%m-%d").isoformat() + "Z": amount
124-
for date, amount in confirmed_history.items()
125-
}
126-
),
127-
"deaths": Timeline(
128-
timeline={
129-
datetime.strptime(date, "%Y-%m-%d").isoformat() + "Z": amount
130-
for date, amount in deaths_history.items()
131-
}
132-
),
133-
"recovered": Timeline(),
134-
},
135-
)
136-
)
137111
LOGGER.info(f"{data_id} Data normalized")
138112
# save the results to distributed cache
139113
# TODO: fix json serialization

0 commit comments

Comments
 (0)