Skip to content

Commit 5aab1fb

Browse files
committed
made variables inside of httputils.py private and incorporated use of get methods
1 parent 330b212 commit 5aab1fb

File tree

5 files changed

+35
-22
lines changed

5 files changed

+35
-22
lines changed

app/main.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from .config import get_settings
1717
from .data import data_source
1818
from .routers import V1, V2
19-
from .utils.httputils import setup_client_session, teardown_client_session
19+
from .utils.httputils import Session
2020

2121
# ############
2222
# FastAPI App
@@ -37,8 +37,8 @@
3737
version="2.0.4",
3838
docs_url="/",
3939
redoc_url="/docs",
40-
on_startup=[setup_client_session],
41-
on_shutdown=[teardown_client_session],
40+
on_startup=[Session.setup_client_session],
41+
on_shutdown=[Session.teardown_client_session],
4242
)
4343

4444
# #####################

app/services/location/csbs.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ async def get_locations():
5252
locations = cache_results
5353
else:
5454
LOGGER.info(f"{data_id} shared cache empty")
55-
async with httputils.CLIENT_SESSION.get(BASE_URL) as response:
55+
async with httputils.Session.getClientSession().get(BASE_URL) as response:
5656
text = await response.text()
5757

5858
LOGGER.debug(f"{data_id} Data received")
@@ -84,7 +84,8 @@ async def get_locations():
8484
# Coordinates.
8585
Coordinates(item["Latitude"], item["Longitude"]),
8686
# Last update (parse as ISO).
87-
datetime.strptime(last_update, "%Y-%m-%d %H:%M").isoformat() + "Z",
87+
datetime.strptime(
88+
last_update, "%Y-%m-%d %H:%M").isoformat() + "Z",
8889
# Statistics.
8990
int(item["Confirmed"] or 0),
9091
int(item["Death"] or 0),

app/services/location/jhu.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ async def get_category(category):
6868

6969
# Request the data
7070
LOGGER.info(f"{data_id} Requesting data...")
71-
async with httputils.CLIENT_SESSION.get(url) as response:
71+
async with httputils.Session.getClientSession().get(url) as response:
7272
text = await response.text()
7373

7474
LOGGER.debug(f"{data_id} Data received")
@@ -82,10 +82,12 @@ async def get_category(category):
8282

8383
for item in data:
8484
# Filter out all the dates.
85-
dates = dict(filter(lambda element: date_util.is_date(element[0]), item.items()))
85+
dates = dict(
86+
filter(lambda element: date_util.is_date(element[0]), item.items()))
8687

8788
# Make location history from dates.
88-
history = {date: int(float(amount or 0)) for date, amount in dates.items()}
89+
history = {date: int(float(amount or 0))
90+
for date, amount in dates.items()}
8991

9092
# Country for this location.
9193
country = item["Country/Region"]
@@ -101,7 +103,7 @@ async def get_category(category):
101103
"country_code": countries.country_code(country),
102104
"province": item["Province/State"],
103105
# Coordinates.
104-
"coordinates": {"lat": item["Lat"], "long": item["Long"],},
106+
"coordinates": {"lat": item["Lat"], "long": item["Long"], },
105107
# History.
106108
"history": history,
107109
# Latest statistic.
@@ -178,7 +180,8 @@ async def get_locations():
178180
location["country"],
179181
location["province"],
180182
# Coordinates.
181-
Coordinates(latitude=coordinates["lat"], longitude=coordinates["long"]),
183+
Coordinates(
184+
latitude=coordinates["lat"], longitude=coordinates["long"]),
182185
# Last update.
183186
datetime.utcnow().isoformat() + "Z",
184187
# Timelines (parse dates as ISO).

app/services/location/nyt.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ async def get_locations():
8585
locations = cache_results
8686
else:
8787
LOGGER.info(f"{data_id} shared cache empty")
88-
async with httputils.CLIENT_SESSION.get(BASE_URL) as response:
88+
async with httputils.Session.getClientSession().get(BASE_URL) as response:
8989
text = await response.text()
9090

9191
LOGGER.debug(f"{data_id} Data received")
@@ -104,18 +104,21 @@ async def get_locations():
104104
# Make location history for confirmed and deaths from dates.
105105
# List is tuples of (date, amount) in order of increasing dates.
106106
confirmed_list = histories["confirmed"]
107-
confirmed_history = {date: int(amount or 0) for date, amount in confirmed_list}
107+
confirmed_history = {date: int(amount or 0)
108+
for date, amount in confirmed_list}
108109

109110
deaths_list = histories["deaths"]
110-
deaths_history = {date: int(amount or 0) for date, amount in deaths_list}
111+
deaths_history = {date: int(amount or 0)
112+
for date, amount in deaths_list}
111113

112114
# Normalize the item and append to locations.
113115
locations.append(
114116
NYTLocation(
115117
id=idx,
116118
state=county_state[1],
117119
county=county_state[0],
118-
coordinates=Coordinates(None, None), # NYT does not provide coordinates
120+
# NYT does not provide coordinates
121+
coordinates=Coordinates(None, None),
119122
last_updated=datetime.utcnow().isoformat() + "Z", # since last request
120123
timelines={
121124
"confirmed": Timeline(

app/utils/httputils.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,14 @@
66

77
class Session:
88
# Singleton aiohttp.ClientSession instance.
9-
CLIENT_SESSION: ClientSession
10-
LOGGER = logging.getLogger(__name__)
9+
__CLIENT_SESSION: ClientSession
10+
__LOGGER = logging.getLogger(__name__)
11+
12+
def getClientSession(self):
13+
return self.__CLIENT_SESSION
14+
15+
def getLogger(self):
16+
return self.__LOGGER
1117

1218
async def setup_client_session(self):
1319
"""Set up the application-global aiohttp.ClientSession instance.
@@ -16,13 +22,13 @@ async def setup_client_session(self):
1622
See: https://docs.aiohttp.org/en/stable/client_quickstart.html#make-a-request
1723
1824
"""
19-
global CLIENT_SESSION # pylint: disable=global-statement
20-
self.LOGGER.info("Setting up global aiohttp.ClientSession.")
21-
CLIENT_SESSION = ClientSession()
25+
# global CLIENT_SESSION # pylint: disable=global-statement
26+
self.getLogger().info("Setting up global aiohttp.ClientSession.")
27+
self.getClientSession() = ClientSession()
2228

2329
async def teardown_client_session(self):
2430
"""Close the application-global aiohttp.ClientSession.
2531
"""
26-
global CLIENT_SESSION # pylint: disable=global-statement
27-
self.LOGGER.info("Closing global aiohttp.ClientSession.")
28-
await CLIENT_SESSION.close()
32+
# global CLIENT_SESSION # pylint: disable=global-statement
33+
self.getLogger().info("Closing global aiohttp.ClientSession.")
34+
await self.getClientSession().close()

0 commit comments

Comments
 (0)