/
apiwrap.py
88 lines (77 loc) · 2.71 KB
/
apiwrap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""API Client wrapper for CLI."""
import os
import sys
import textwrap
from pathlib import Path
from logging import debug
from .api import TimewebCloud
from .api import exceptions as exc
from .commands.common import load_config
def request_handler(func):
"""Error handler decorator for requests. Wrap API exceptions
and exit with human-readable error message.
"""
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except exc.NetworkError as err:
sys.exit(f"Error: {err}")
except exc.UnauthorizedError as err:
sys.exit(
textwrap.dedent(
f"""
Error: {err}
Please check your API access token. Try run 'twc config'
"""
).strip()
)
except exc.MalformedResponseError as err:
sys.exit(
textwrap.dedent(
f"""
Error: API returned malformed response: {err}
Try run command with '--verbose' option for details.
"""
).strip()
)
except exc.UnexpectedResponseError as err:
sys.exit(
textwrap.dedent(
f"""
Error: API returned unexpected response: {err}
Try run command with '--verbose' option for details.
"""
).strip()
)
except exc.TimewebCloudException as err:
sys.exit(
textwrap.dedent(
f"""
Error ocurred.
Status code: {err.status_code}
Error code: {err.error_code}
Message: {err.message}
Response ID: {err.response_id}
"""
).strip()
)
return wrapper
def create_client(config: Path, profile: str, **kwargs) -> TimewebCloud:
"""API client wrapper. Read configuration file and return
`TimewebCloud` object with decorator.
"""
token = os.getenv("TWC_TOKEN")
log_settings = os.getenv("TWC_LOG")
if log_settings:
for param in log_settings.split(","):
if param == "log_response":
kwargs["log_response_body"] = True
if token:
debug("Config: use API token from environment")
else:
try:
debug(f"Config: file={config}, profile={profile}")
token = load_config(config)[profile]["token"]
except KeyError:
sys.exit(f"Error: Profile '{profile}' not found in {config}")
return TimewebCloud(token, request_decorator=request_handler, **kwargs)