Skip to content

Commit

Permalink
formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Kilo59 committed May 9, 2020
1 parent fb8abdf commit 163c238
Show file tree
Hide file tree
Showing 14 changed files with 30 additions and 80 deletions.
14 changes: 2 additions & 12 deletions app/location/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,7 @@ class Location: # pylint: disable=too-many-instance-attributes
"""

def __init__(
self,
id,
country,
province,
coordinates,
last_updated,
confirmed,
deaths,
recovered,
self, id, country, province, coordinates, last_updated, confirmed, deaths, recovered,
): # pylint: disable=too-many-arguments
# General info.
self.id = id
Expand All @@ -43,9 +35,7 @@ def country_code(self):
:returns: The country code.
:rtype: str
"""
return (
countries.country_code(self.country) or countries.DEFAULT_COUNTRY_CODE
).upper()
return (countries.country_code(self.country) or countries.DEFAULT_COUNTRY_CODE).upper()

@property
def country_population(self):
Expand Down
4 changes: 1 addition & 3 deletions app/location/csbs.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ def __init__(self, id, state, county, coordinates, last_updated, confirmed, deat
self.state = state
self.county = county

def serialize(
self, timelines=False
): # pylint: disable=arguments-differ,unused-argument
def serialize(self, timelines=False): # pylint: disable=arguments-differ,unused-argument
"""
Serializes the location into a dict.
Expand Down
4 changes: 1 addition & 3 deletions app/location/nyt.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ def __init__(self, id, state, county, coordinates, last_updated, timelines):
self.state = state
self.county = county

def serialize(
self, timelines=False
): # pylint: disable=arguments-differ,unused-argument
def serialize(self, timelines=False): # pylint: disable=arguments-differ,unused-argument
"""
Serializes the location into a dict.
Expand Down
11 changes: 3 additions & 8 deletions app/routers/v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ class Sources(str, enum.Enum):


@V2.get("/latest", response_model=LatestResponse)
async def get_latest(
request: Request, source: Sources = "jhu"
): # pylint: disable=unused-argument
async def get_latest(request: Request, source: Sources = "jhu"): # pylint: disable=unused-argument
"""
Getting latest amount of total confirmed cases, deaths, and recoveries.
"""
Expand All @@ -37,9 +35,7 @@ async def get_latest(


# pylint: disable=unused-argument,too-many-arguments,redefined-builtin
@V2.get(
"/locations", response_model=LocationsResponse, response_model_exclude_unset=True
)
@V2.get("/locations", response_model=LocationsResponse, response_model_exclude_unset=True)
async def get_locations(
request: Request,
source: Sources = "jhu",
Expand Down Expand Up @@ -78,8 +74,7 @@ async def get_locations(
pass
if not locations:
raise HTTPException(
404,
detail=f"Source `{source}` does not have the desired location data.",
404, detail=f"Source `{source}` does not have the desired location data.",
)

# Return final serialized data.
Expand Down
1 change: 0 additions & 1 deletion app/services/location/csbs.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from asyncache import cached
from cachetools import TTLCache


from ...caches import check_cache, load_cache
from ...coordinates import Coordinates
from ...location.csbs import CSBSLocation
Expand Down
10 changes: 3 additions & 7 deletions app/services/location/jhu.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,7 @@ async def get_category(category):

for item in data:
# Filter out all the dates.
dates = dict(
filter(lambda element: date_util.is_date(element[0]), item.items())
)
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()}
Expand Down Expand Up @@ -178,15 +176,13 @@ async def get_locations():
{
"confirmed": Timeline(
{
datetime.strptime(date, "%m/%d/%y").isoformat()
+ "Z": amount
datetime.strptime(date, "%m/%d/%y").isoformat() + "Z": amount
for date, amount in timelines["confirmed"].items()
}
),
"deaths": Timeline(
{
datetime.strptime(date, "%m/%d/%y").isoformat()
+ "Z": amount
datetime.strptime(date, "%m/%d/%y").isoformat() + "Z": amount
for date, amount in timelines["deaths"].items()
}
),
Expand Down
22 changes: 6 additions & 16 deletions app/services/location/nyt.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from asyncache import cached
from cachetools import TTLCache


from ...caches import check_cache, load_cache
from ...coordinates import Coordinates
from ...location.nyt import NYTLocation
Expand Down Expand Up @@ -37,9 +36,7 @@ async def get(self, loc_id): # pylint: disable=arguments-differ


# Base URL for fetching category.
BASE_URL = (
"https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv"
)
BASE_URL = "https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv"


def get_grouped_locations_dict(data):
Expand Down Expand Up @@ -107,9 +104,7 @@ async def get_locations():
# Make location history for confirmed and deaths from dates.
# List is tuples of (date, amount) in order of increasing dates.
confirmed_list = histories["confirmed"]
confirmed_history = {
date: int(amount or 0) for date, amount in confirmed_list
}
confirmed_history = {date: int(amount or 0) for date, amount in confirmed_list}

deaths_list = histories["deaths"]
deaths_history = {date: int(amount or 0) for date, amount in deaths_list}
Expand All @@ -120,23 +115,18 @@ async def get_locations():
id=idx,
state=county_state[1],
county=county_state[0],
coordinates=Coordinates(
None, None
), # NYT does not provide coordinates
last_updated=datetime.utcnow().isoformat()
+ "Z", # since last request
coordinates=Coordinates(None, None), # NYT does not provide coordinates
last_updated=datetime.utcnow().isoformat() + "Z", # since last request
timelines={
"confirmed": Timeline(
{
datetime.strptime(date, "%Y-%m-%d").isoformat()
+ "Z": amount
datetime.strptime(date, "%Y-%m-%d").isoformat() + "Z": amount
for date, amount in confirmed_history.items()
}
),
"deaths": Timeline(
{
datetime.strptime(date, "%Y-%m-%d").isoformat()
+ "Z": amount
datetime.strptime(date, "%Y-%m-%d").isoformat() + "Z": amount
for date, amount in deaths_history.items()
}
),
Expand Down
18 changes: 6 additions & 12 deletions app/utils/populations.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,23 +28,17 @@ def fetch_populations(save=False):

# Fetch the countries.
try:
countries = requests.get(
GEONAMES_URL, params={"username": "dperic"}, timeout=1.25
).json()["geonames"]
countries = requests.get(GEONAMES_URL, params={"username": "dperic"}, timeout=1.25).json()[
"geonames"
]
# Go through all the countries and perform the mapping.
for country in countries:
mappings.update(
{country["countryCode"]: int(country["population"]) or None}
)
mappings.update({country["countryCode"]: int(country["population"]) or None})

if mappings and save:
LOGGER.info(
f"Saving population data to {app.io.save(GEONAMES_BACKUP_PATH, mappings)}"
)
LOGGER.info(f"Saving population data to {app.io.save(GEONAMES_BACKUP_PATH, mappings)}")
except (json.JSONDecodeError, KeyError, requests.exceptions.Timeout) as err:
LOGGER.warning(
f"Error pulling population data. {err.__class__.__name__}: {err}"
)
LOGGER.warning(f"Error pulling population data. {err.__class__.__name__}: {err}")
mappings = app.io.load(GEONAMES_BACKUP_PATH)
LOGGER.info(f"Using backup data from {GEONAMES_BACKUP_PATH}")
# Finally, return the mappings.
Expand Down
6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tool.black]
line-length = 88
line-length = 100
target-version = ['py36', 'py37', 'py38']
include = '\.pyi?$'
exclude = '''
Expand All @@ -23,7 +23,7 @@ multi_line_output = 3
include_trailing_comma = "True"
force_grid_wrap = 0
use_parentheses = "True"
line_length = 88
line_length = 100

[tool.pylint.master]
extension-pkg-whitelist = "pydantic"
Expand All @@ -42,7 +42,7 @@ logging-modules = "logging"
allow-wildcard-with-all = "no"
[tool.pylint.format]
indent-after-paren = "4"
max-line-length = "120" # matches black setting
max-line-length = "100" # matches black setting
max-module-lines = "800"
no-space-check = '''
trailing-comma,
Expand Down
4 changes: 1 addition & 3 deletions tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ def fmt(ctx, targets="."):


@invoke.task
def check(
ctx, fmt=False, sort=False, diff=False
): # pylint: disable=redefined-outer-name
def check(ctx, fmt=False, sort=False, diff=False): # pylint: disable=redefined-outer-name
"""Check code format and import order."""
if not any([fmt, sort]):
fmt = True
Expand Down
4 changes: 1 addition & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,7 @@ def read_file(self, state):
state = state.lower()

# Determine filepath.
filepath = os.path.join(
os.path.dirname(__file__), "example_data/{}.csv".format(state)
)
filepath = os.path.join(os.path.dirname(__file__), "example_data/{}.csv".format(state))

# Return fake response.
print("Try to read {}".format(filepath))
Expand Down
4 changes: 1 addition & 3 deletions tests/test_coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@
from app import coordinates


@pytest.mark.parametrize(
"latitude, longitude", [("1", "2"), (100, "2"), (-3, 0), (-10, -10000000)]
)
@pytest.mark.parametrize("latitude, longitude", [("1", "2"), (100, "2"), (-3, 0), (-10, -10000000)])
def test_coordinates_class(latitude, longitude):
coord_obj = coordinates.Coordinates(latitude=latitude, longitude=longitude)

Expand Down
4 changes: 1 addition & 3 deletions tests/test_populations.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,6 @@
],
)
def test_fetch_populations(body_arg, json_arg):
responses.add(
responses.GET, app.utils.populations.GEONAMES_URL, body=body_arg, json=json_arg
)
responses.add(responses.GET, app.utils.populations.GEONAMES_URL, body=body_arg, json=json_arg)

assert app.utils.populations.fetch_populations()
4 changes: 1 addition & 3 deletions tests/test_timeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ def test_timeline_class():
# validate serialize
check_serialize = {
"latest": 7,
"timeline": OrderedDict(
[("1/22/20", 2), ("1/23/20", 3), ("1/24/20", 5), ("1/25/20", 7),]
),
"timeline": OrderedDict([("1/22/20", 2), ("1/23/20", 3), ("1/24/20", 5), ("1/25/20", 7),]),
}

assert dict(history_data.serialize()) == check_serialize

0 comments on commit 163c238

Please sign in to comment.