Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encapsulated location related methods #54

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ venv.bak/

# mkdocs documentation
/site
.idea

# mypy
.mypy_cache/
Expand Down
62 changes: 21 additions & 41 deletions COVID19Py/covid19.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from typing import Dict, List
import requests
import json
from .sources import Reterivedata
from .location import Location


class COVID19(object):
default_url = "https://covid-tracker-us.herokuapp.com"
Expand All @@ -27,7 +30,9 @@ def __init__(self, url="https://covid-tracker-us.herokuapp.com", data_source='jh
self.url = mirror["url"]
result = None
try:
result = self._getSources()
retrieve = Reterivedata(url= url, data_source= data_source,
endpoint="/v2/sources", params=None)
result = retrieve.getSources()
except Exception as e:
# URL did not work, reset it and move on
self.url = ""
Expand All @@ -44,7 +49,9 @@ def __init__(self, url="https://covid-tracker-us.herokuapp.com", data_source='jh
else:
self.url = url

self._valid_data_sources = self._getSources()
retrieve = Reterivedata(url=url, data_source=data_source,
endpoint="/v2/sources", params=None)
self._valid_data_sources = retrieve.getSources()
if data_source not in self._valid_data_sources:
raise ValueError("Invalid data source. Expected one of: %s" % self._valid_data_sources)
self.data_source = data_source
Expand All @@ -64,14 +71,8 @@ def _getSources(self):
response.raise_for_status()
return response.json()["sources"]

def _request(self, endpoint, params=None):
if params is None:
params = {}
response = requests.get(self.url + endpoint, {**params, "source":self.data_source})
response.raise_for_status()
return response.json()

def getAll(self, timelines=False):

self._update(timelines)
return self.latestData

Expand All @@ -95,7 +96,8 @@ def getLatest(self) -> List[Dict[str, int]]:
"""
:return: The latest amount of total confirmed cases, deaths, and recoveries.
"""
data = self._request("/v2/latest")
retrieve = Reterivedata(self.url, self.data_source, "/v2/latest", None)
data = retrieve.retreive()
return data["latest"]

def getLocations(self, timelines=False, rank_by: str = None) -> List[Dict]:
Expand All @@ -105,54 +107,32 @@ def getLocations(self, timelines=False, rank_by: str = None) -> List[Dict]:
:param rank_by: Category to rank results by. ex: confirmed
:return: List of dictionaries representing all affected locations.
"""
data = None
if timelines:
data = self._request("/v2/locations", {"timelines": str(timelines).lower()})
else:
data = self._request("/v2/locations")

data = data["locations"]

ranking_criteria = ['confirmed', 'deaths', 'recovered']
if rank_by is not None:
if rank_by not in ranking_criteria:
raise ValueError("Invalid ranking criteria. Expected one of: %s" % ranking_criteria)

ranked = sorted(data, key=lambda i: i['latest'][rank_by], reverse=True)
data = ranked

return data
location = Location(url=self.url, data_source=self.data_source)
return location.getLocations(timelines = timelines, rank_by = rank_by)

def getLocationByCountryCode(self, country_code, timelines=False) -> List[Dict]:
"""
:param country_code: String denoting the ISO 3166-1 alpha-2 code (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the country
:param timelines: Whether timeline information should be returned as well.
:return: A list of areas that correspond to the country_code. If the country_code is invalid, it returns an empty list.
"""
data = None
if timelines:
data = self._request("/v2/locations", {"country_code": country_code, "timelines": str(timelines).lower()})
else:
data = self._request("/v2/locations", {"country_code": country_code})
return data["locations"]

location = Location(url=self.url, data_source=self.data_source)
return location.getLocationByCountryCode(country_code= country_code, timelines=timelines)

def getLocationByCountry(self, country, timelines=False) -> List[Dict]:
"""
:param country: String denoting name of the country
:param timelines: Whether timeline information should be returned as well.
:return: A list of areas that correspond to the country name. If the country is invalid, it returns an empty list.
"""
data = None
if timelines:
data = self._request("/v2/locations", {"country": country, "timelines": str(timelines).lower()})
else:
data = self._request("/v2/locations", {"country": country})
return data["locations"]
location = Location(url=self.url, data_source=self.data_source)
return location.getLocationByCountry(country = country, timelines=timelines)

def getLocationById(self, country_id: int):
"""
:param country_id: Country Id, an int
:return: A dictionary with case information for the specified location.
"""
data = self._request("/v2/locations/" + str(country_id))
return data["location"]
location = Location(url=self.url, data_source=self.data_source)
return location.getLocationById(country_id = country_id)
81 changes: 81 additions & 0 deletions COVID19Py/location.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
from typing import List, Dict

from .sources import Reterivedata


class Location:
def __init__(self, url, data_source):
self.url = url
self.data_source = data_source

def getLocations(self, timelines=False, rank_by: str = None) -> List[Dict]:
"""
Gets all locations affected by COVID-19, as well as latest case data.
:param timelines: Whether timeline information should be returned as well.
:param rank_by: Category to rank results by. ex: confirmed
:return: List of dictionaries representing all affected locations.
"""
data = None
if timelines:
retrieve = Reterivedata(self.url, self.data_source, "/v2/locations",
{"timelines": str(timelines).lower()})
data = retrieve.retreive()
else:
retrieve = Reterivedata(self.url, self.data_source, "/v2/locations")
data = retrieve.retreive()

data = data["locations"]

ranking_criteria = ['confirmed', 'deaths', 'recovered']
if rank_by is not None:
if rank_by not in ranking_criteria:
raise ValueError("Invalid ranking criteria. Expected one of: %s" % ranking_criteria)

ranked = sorted(data, key=lambda i: i['latest'][rank_by], reverse=True)
data = ranked

return data

def getLocationByCountryCode(self, country_code, timelines=False) -> List[Dict]:
"""
:param country_code: String denoting the ISO 3166-1 alpha-2 code (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the country
:param timelines: Whether timeline information should be returned as well.
:return: A list of areas that correspond to the country_code. If the country_code is invalid, it returns an empty list.
"""
data = None
if timelines:
retrieve = Reterivedata(self.url, self.data_source, "/v2/locations",
{"country_code": country_code, "timelines": str(timelines).lower()})
data = retrieve.retreive()
else:
retrieve = Reterivedata(self.url, self.data_source, "/v2/locations",
{"country_code": country_code})
data = retrieve.retreive()

return data["locations"]

def getLocationByCountry(self, country, timelines=False) -> List[Dict]:
"""
:param country: String denoting name of the country
:param timelines: Whether timeline information should be returned as well.
:return: A list of areas that correspond to the country name. If the country is invalid, it returns an empty list.
"""
data = None
if timelines:
retrieve = Reterivedata(self.url, self.data_source, "/v2/locations",
{"country": country, "timelines": str(timelines).lower()})
data = retrieve.retreive()
else:
retrieve = Reterivedata(self.url, self.data_source, "/v2/locations",
{"country": country})
data = retrieve.retreive()
return data["locations"]

def getLocationById(self, country_id: int):
"""
:param country_id: Country Id, an int
:return: A dictionary with case information for the specified location.
"""
retrieve = Reterivedata(self.url, self.data_source, "/v2/locations/" + str(country_id))
data = retrieve.retreive()
return data["location"]
21 changes: 21 additions & 0 deletions COVID19Py/sources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import requests


class Reterivedata:
def __init__(self, url, data_source, endpoint, params=None):
self.url = url
self.data_source = data_source
self.endpoint = endpoint
self.params = params if params else None

def retreive(self):
if self.params is None:
self.params = {}
response = requests.get(self.url + self.endpoint, {**self.params, "source": self.data_source})
response.raise_for_status()
return response.json()

def getSources(self):
response = requests.get(self.url + "/v2/sources")
response.raise_for_status()
return response.json()["sources"]
18 changes: 10 additions & 8 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 2 additions & 3 deletions examples/latest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import COVID19Py

covid19 = COVID19Py.COVID19()
from COVID19Py import COVID19

covid19 = COVID19()
print(covid19.getLatest())
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
requests~=2.24.0
requests~=2.24.0
Expand Down