Skip to content

Commit

Permalink
feat: Improve exceptions handling with loguru
Browse files Browse the repository at this point in the history
  • Loading branch information
pawamoy committed Aug 7, 2019
1 parent 03e7d5b commit e0ded18
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 16 deletions.
48 changes: 44 additions & 4 deletions poetry.lock

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

1 change: 1 addition & 0 deletions pyproject.toml
Expand Up @@ -21,6 +21,7 @@ include = [
[tool.poetry.dependencies]
python = "^3.6"
requests = "*"
loguru = "^0.2.5"

[tool.poetry.dev-dependencies]
bandit = "^1.5"
Expand Down
6 changes: 6 additions & 0 deletions src/aria2p/__init__.py
Expand Up @@ -8,20 +8,26 @@
please refer to the README.md included in this package to get the link to the official documentation.
"""

from loguru import logger

from .api import API
from .client import Client, ClientException
from .downloads import BitTorrent, Download, File
from .options import Options
from .stats import Stats

logger.disable("aria2p")

__all__ = ["API", "ClientException", "Client", "Download", "BitTorrent", "File", "Options", "Stats"]

# TODO: use proper logging messages (esp. in except: pass)
# TODO: maybe add type annotations
# TODO: handle both str and pathlib.Path for paths consistently
# TODO: add command "add" for normal downloads!!
# TODO: add "--options" options for "add" commands
# TODO: in API, support download arguments to be both Download or str (GID)?
# TODO: add clean parameter for api.move_files method (to clean .aria2 files)
# TODO: add value verification for options (see man page)

# Roadmap:
# - feature: Ability to hide metadata downloads (magnet URIs)
Expand Down
21 changes: 17 additions & 4 deletions src/aria2p/api.py
Expand Up @@ -6,6 +6,8 @@
from base64 import b64encode
from pathlib import Path

from loguru import logger

from .client import Client, ClientException
from .downloads import Download
from .options import Options
Expand Down Expand Up @@ -332,18 +334,23 @@ def remove(self, downloads, force=False):
try:
removed_gid = remove_func(download.gid)
except ClientException as e:
logger.debug(f"Failed to remove download {download.gid}")
logger.opt(exception=True).trace(e)
result.append(e)
else:
result.append(True)
try:
self.client.remove_download_result(download.gid)
except ClientException:
pass
except ClientException as ee:
logger.debug(f"Failed to remove download result {download.gid}")
logger.opt(exception=True).trace(ee)
if removed_gid != download.gid:
logger.debug(f"Removed download GID#{removed_gid} is different than download GID#{download.gid}")
try:
self.client.remove_download_result(removed_gid)
except ClientException:
pass
except ClientException as ee:
logger.debug(f"Failed to remove download result {removed_gid}")
logger.opt(exception=True).trace(ee)

return result

Expand Down Expand Up @@ -382,6 +389,8 @@ def pause(self, downloads, force=False):
try:
pause_func(download.gid)
except ClientException as e:
logger.debug(f"Failed to pause download {download.gid}")
logger.opt(exception=True).trace(e)
result.append(e)
else:
result.append(True)
Expand Down Expand Up @@ -423,6 +432,8 @@ def resume(self, downloads):
try:
self.client.unpause(download.gid)
except ClientException as e:
logger.debug(f"Failed to resume download {download.gid}")
logger.opt(exception=True).trace(e)
result.append(e)
else:
result.append(True)
Expand Down Expand Up @@ -461,6 +472,8 @@ def purge(self, downloads):
try:
self.client.remove_download_result(download.gid)
except ClientException as e:
logger.debug(f"Failed to purge download result {download.gid}")
logger.opt(exception=True).trace(e)
result.append(e)
else:
result.append(True)
Expand Down
14 changes: 14 additions & 0 deletions src/aria2p/cli.py
Expand Up @@ -20,6 +20,7 @@
import sys

import requests
from loguru import logger

from aria2p import Download

Expand All @@ -36,6 +37,10 @@ def main(args=None):
check_args(parser, args)
kwargs = args.__dict__

logger.remove()
logger.configure(handlers=[{"sink": sys.stderr, "level": kwargs.pop("log_level")}])
logger.enable("aria2p")

api = API(Client(host=kwargs.pop("host"), port=kwargs.pop("port"), secret=kwargs.pop("secret")))

# Warn if no aria2 daemon process seems to be running
Expand Down Expand Up @@ -104,6 +109,15 @@ def get_parser():
global_options.add_argument(
"-s", "--secret", dest="secret", default="", help="Secret token to use to connect to the remote server."
)
global_options.add_argument(
"-L",
"--log-level",
dest="log_level",
default="ERROR",
help="Log level to use",
choices=("TRACE", "DEBUG", "INFO", "SUCCESS", "WARNING", "ERROR", "CRITICAL"),
type=str.upper,
)

# ========= SUBPARSERS ========= #
subparsers = parser.add_subparsers(dest="subcommand", title="Commands", metavar="", prog="aria2p")
Expand Down
28 changes: 20 additions & 8 deletions src/aria2p/downloads.py
Expand Up @@ -5,6 +5,8 @@
from datetime import datetime, timedelta
from pathlib import Path

from loguru import logger

from .client import ClientException
from .utils import bool_or_value, human_readable_bytes, human_readable_timedelta

Expand Down Expand Up @@ -244,8 +246,9 @@ def root_files_paths(self):
continue
try:
relative_path = file.path.relative_to(self.dir)
except ValueError:
pass # TODO: log
except ValueError as e:
logger.warning(f"Can't determine file path '{file.path}' relative to '{self.dir}'")
logger.opt(exception=True).trace(e)
else:
path = self.dir / relative_path.parts[0]
if path not in paths:
Expand Down Expand Up @@ -517,8 +520,9 @@ def followed_by(self):
for gid in self.followed_by_ids:
try:
result.append(self.api.get_download(gid))
except ClientException:
pass
except ClientException as e:
logger.warning(f"Can't find download with GID {gid}, try to update download {self.gid} ({id(self)}")
logger.opt(exception=True).trace(e)
self._followed_by = result
return self._followed_by

Expand All @@ -541,8 +545,12 @@ def following(self):
if not self._following:
try:
self._following = self.api.get_download(self.following_id)
except ClientException:
return None
except ClientException as e:
logger.warning(
f"Can't find download with GID {self.following_id}, try to update download {self.gid} ({id(self)}"
)
logger.opt(exception=True).trace(e)
self._following = None
return self._following

@property
Expand All @@ -566,8 +574,12 @@ def belongs_to(self):
if not self._belongs_to:
try:
self._belongs_to = self.api.get_download(self.belongs_to_id)
except ClientException:
return None
except ClientException as e:
logger.warning(
f"Can't find download with GID {self.belongs_to_id}, try to update download {self.gid} ({id(self)}"
)
logger.opt(exception=True).trace(e)
self._belongs_to = None
return self._belongs_to

@property
Expand Down

0 comments on commit e0ded18

Please sign in to comment.