Skip to content

Commit

Permalink
Fix bugs and bump version number
Browse files Browse the repository at this point in the history
  • Loading branch information
parafoxia committed Jul 23, 2021
1 parent 198c91e commit 717c7df
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 30 deletions.
2 changes: 1 addition & 1 deletion analytix/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
__productname__ = "analytix"
__version__ = "2.0.0.dev4"
__version__ = "2.0.0.dev5"
__description__ = "A simple yet powerful API wrapper to make getting analytical information from the YouTube Analytics API easier than ever."
__url__ = "https://github.com/parafoxia/analytix"
__docs__ = "https://analytix.readthedocs.io/en/latest/"
Expand Down
13 changes: 0 additions & 13 deletions analytix/packages.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
__all__ = (
"PANDAS_AVAILABLE",
"NUMPY_AVAILABLE",
"requires_pandas",
"requires_numpy",
)

from pkg_resources import working_set
Expand All @@ -11,7 +9,6 @@

_packages = [p.key for p in working_set]
PANDAS_AVAILABLE = "pandas" in _packages
NUMPY_AVAILABLE = "numpy" in _packages


def requires_pandas(func):
Expand All @@ -22,13 +19,3 @@ def wrapper(*args, **kwargs):
return func(*args, **kwargs)

return wrapper


def requires_numpy(func):
def wrapper(*args, **kwargs):
if not NUMPY_AVAILABLE:
raise MissingOptionalComponents("numpy is not installed")

return func(*args, **kwargs)

return wrapper
31 changes: 16 additions & 15 deletions analytix/youtube/analytics/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@

if PANDAS_AVAILABLE:
import pandas as pd
if NUMPY_AVAILABLE:
import numpy as np


class YouTubeAnalytics:
Expand Down Expand Up @@ -250,6 +248,7 @@ def retrieve(
logging.debug(f"URL: {url}")

if not self._token:
logging.debug("Authorising...")
self.authorise()

with requests.get(
Expand All @@ -262,23 +261,18 @@ def retrieve(
raise HTTPError(f"{error['code']}: {error['message']}")

logging.info("Creating report...")
return YouTubeAnalyticsReport(
f"{rtype}", [c["name"] for c in data["columnHeaders"]], data["rows"]
)
return YouTubeAnalyticsReport(f"{rtype}", data)


class YouTubeAnalyticsReport:
__slots__ = ("type", "columns", "rows", "_ncolumns", "_nrows")
__slots__ = ("type", "data", "columns", "_ncolumns", "_nrows")

def __init__(self, type, columns, rows):
def __init__(self, type, data):
self.type = type
self.columns = columns
if NUMPY_AVAILABLE:
self.rows = np.array(rows)
else:
self.rows = rows
self.data = data
self.columns = [c["name"] for c in data["columnHeaders"]]
self._ncolumns = len(self.columns)
self._nrows = len(self.rows)
self._nrows = len(data["rows"])

def __repr__(self):
return f"<YouTubeAnalyticsReport shape={self.shape!r}>"
Expand All @@ -289,20 +283,27 @@ def shape(self):

@requires_pandas
def to_dataframe(self):
df = pd.DataFrame(self.rows)
df = pd.DataFrame(self.data["rows"])
df.columns = self.columns
if "day" in df.columns:
df["day"] = pd.to_datetime(df["day"], format="%Y-%m-%d")
if "month" in df.columns:
df["month"] = pd.to_datetime(df["month"], format="%Y-%m")
return df

def to_json(self, path, *, indent=4):
if not path.endswith(".json"):
path += ".json"

with open(path, mode="w", encoding="utf-8") as f:
json.dump(self.data, f, indent=indent, ensure_ascii=False)

def to_csv(self, path, *, delimiter=","):
if not path.endswith(".csv"):
path += ".csv"

with open(path, mode="w", encoding="utf-8") as f:
writer = csv.writer(f, delimiter=delimiter)
writer.writerow(self.columns)
for r in self.rows:
for r in self.data["rows"]:
writer.writerow(r)
2 changes: 1 addition & 1 deletion analytix/youtube/analytics/verify/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def verify(self, against, ftype):
for v in self.values:
k = v.split("==")
if len(k) == 2:
if k[1] != against[k[0]]:
if k[0] in against and (k[1] != against[k[0]]):
raise InvalidRequest(
f"filter '{k[0]}' must be set to '{k[1]}' for the selected report type"
)
Expand Down

0 comments on commit 717c7df

Please sign in to comment.