Skip to content

Commit 2d5f4e3

Browse files
committed
Formatted code using black
1 parent 754b5e1 commit 2d5f4e3

16 files changed

Lines changed: 246 additions & 182 deletions

File tree

amazon_paapi/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Amazon Product Advertising API wrapper for Python"""
22

3-
__author__ = 'Sergio Abad'
3+
__author__ = "Sergio Abad"
44

55
from .api import AmazonApi
66
from .tools import get_asin

amazon_paapi/api.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,6 @@ def get_items(
6464
include_unavailable: bool = False,
6565
**kwargs
6666
) -> List[models.Item]:
67-
6867
"""Get items information from Amazon.
6968
7069
Args:

amazon_paapi/errors/exceptions.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,43 +3,58 @@
33

44
class AmazonException(Exception):
55
"""Common base class for all Amazon API exceptions."""
6+
67
def __init__(self, reason: str):
78
super().__init__()
89
self.reason = reason
910

1011
def __str__(self) -> str:
11-
return '%s' % self.reason
12+
return "%s" % self.reason
1213

1314

1415
class InvalidArgumentException(AmazonException):
1516
"""Raised when arguments are not correct."""
17+
1618
pass
1719

1820

1921
class AsinNotFoundException(AmazonException):
2022
"""Raised if the ASIN for an item is not found."""
23+
2124
pass
2225

26+
2327
class ApiRequestException(AmazonException):
2428
"""Raised if the request to Amazon API fails"""
29+
2530
pass
2631

32+
2733
class MalformedRequestException(AmazonException):
2834
"""Raised if the request for Amazon API is not correctly formed"""
35+
2936
pass
3037

38+
3139
class ItemsNotFoundException(AmazonException):
3240
"""Raised if no items are found"""
41+
3342
pass
3443

44+
3545
class TooManyRequestsException(AmazonException):
3646
"""Raised when requests limit is reached"""
47+
3748
pass
3849

50+
3951
class InvalidPartnerTagException(AmazonException):
4052
"""Raised if the partner tag is not present or invalid"""
53+
4154
pass
4255

56+
4357
class AssociateValidationException(AmazonException):
4458
"""Raised when credentials are not valid for the selected country"""
59+
4560
pass

amazon_paapi/helpers/arguments.py

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@
99

1010
def get_items_ids(items: Union[str, List[str]]) -> List[str]:
1111
if not isinstance(items, str) and not isinstance(items, List):
12-
raise InvalidArgumentException('Invalid items argument, it should be a string or List of strings')
12+
raise InvalidArgumentException(
13+
"Invalid items argument, it should be a string or List of strings"
14+
)
1315

1416
if isinstance(items, str):
15-
items_ids = items.split(',')
17+
items_ids = items.split(",")
1618
items_ids = [get_asin(x.strip()) for x in items_ids]
1719

1820
else:
@@ -21,7 +23,7 @@ def get_items_ids(items: Union[str, List[str]]) -> List[str]:
2123
if items_ids:
2224
return items_ids
2325

24-
raise AsinNotFoundException('No ASIN codes have been found.')
26+
raise AsinNotFoundException("No ASIN codes have been found.")
2527

2628

2729
def check_search_args(**kwargs):
@@ -30,18 +32,27 @@ def check_search_args(**kwargs):
3032

3133

3234
def _check_search_mandatory_args(**kwargs):
33-
mandatory_args = [kwargs['keywords'], kwargs['actor'], kwargs['artist'],
34-
kwargs['author'], kwargs['brand'], kwargs['title'],
35-
kwargs['browse_node_id'], kwargs['search_index']]
35+
mandatory_args = [
36+
kwargs["keywords"],
37+
kwargs["actor"],
38+
kwargs["artist"],
39+
kwargs["author"],
40+
kwargs["brand"],
41+
kwargs["title"],
42+
kwargs["browse_node_id"],
43+
kwargs["search_index"],
44+
]
3645
if all(arg is None for arg in mandatory_args):
37-
error_message = ('At least one of the following args should be provided: '
38-
'keywords, actor, artist, author, brand, title, browse_node_id or search_index.')
46+
error_message = (
47+
"At least one of the following args should be provided: keywords, actor,"
48+
" artist, author, brand, title, browse_node_id or search_index."
49+
)
3950
raise InvalidArgumentException(error_message)
4051

4152

4253
def _check_search_pagination_args(**kwargs):
43-
error_message = ('Args item_count and item_page should be integers between 1 and 10.')
44-
pagination_args = [kwargs['item_count'], kwargs['item_page']]
54+
error_message = "Args item_count and item_page should be integers between 1 and 10."
55+
pagination_args = [kwargs["item_count"], kwargs["item_page"]]
4556
pagination_args = [arg for arg in pagination_args if arg]
4657

4758
if not all(isinstance(arg, int) for arg in pagination_args):
@@ -52,8 +63,10 @@ def _check_search_pagination_args(**kwargs):
5263

5364

5465
def check_variations_args(**kwargs):
55-
error_message = ('Args variation_count and variation_page should be integers between 1 and 10.')
56-
variation_args = [kwargs['variation_count'], kwargs['variation_page']]
66+
error_message = (
67+
"Args variation_count and variation_page should be integers between 1 and 10."
68+
)
69+
variation_args = [kwargs["variation_count"], kwargs["variation_page"]]
5770
variation_args = [arg for arg in variation_args if arg]
5871

5972
if not all(isinstance(arg, int) for arg in variation_args):
@@ -64,6 +77,6 @@ def check_variations_args(**kwargs):
6477

6578

6679
def check_browse_nodes_args(**kwargs):
67-
if not isinstance(kwargs['browse_node_ids'], List):
68-
error_message = 'Argument browse_node_ids should be a List of strings.'
80+
if not isinstance(kwargs["browse_node_ids"], List):
81+
error_message = "Argument browse_node_ids should be a List of strings."
6982
raise InvalidArgumentException(error_message)

amazon_paapi/helpers/generators.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
from typing import Generator, List
55

66

7-
def get_list_chunks(full_list: List[str], chunk_size: int) -> Generator[List[str], None, None]:
7+
def get_list_chunks(
8+
full_list: List[str], chunk_size: int
9+
) -> Generator[List[str], None, None]:
810
"""Yield successive chunks from List."""
911
for i in range(0, len(full_list), chunk_size):
10-
yield full_list[i:i + chunk_size]
12+
yield full_list[i : i + chunk_size]

amazon_paapi/helpers/items.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
from .. import models
66

77

8-
def sort_items(items: List[models.Item], items_ids: List[str], include_unavailable: bool) -> List[models.Item]:
8+
def sort_items(
9+
items: List[models.Item], items_ids: List[str], include_unavailable: bool
10+
) -> List[models.Item]:
911
sorted_items = []
1012

1113
for asin in items_ids:

amazon_paapi/helpers/requests.py

Lines changed: 76 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,18 @@
3030

3131
def get_items_request(amazon_api, asin_chunk: List[str], **kwargs) -> GetItemsRequest:
3232
try:
33-
return GetItemsRequest(resources=_get_request_resources(GetItemsResource),
34-
partner_type=PartnerType.ASSOCIATES,
35-
marketplace=amazon_api._marketplace,
36-
partner_tag=amazon_api._tag,
37-
item_ids=asin_chunk,
38-
**kwargs)
33+
return GetItemsRequest(
34+
resources=_get_request_resources(GetItemsResource),
35+
partner_type=PartnerType.ASSOCIATES,
36+
marketplace=amazon_api._marketplace,
37+
partner_tag=amazon_api._tag,
38+
item_ids=asin_chunk,
39+
**kwargs
40+
)
3941
except TypeError as e:
40-
raise MalformedRequestException('Parameters for get_items request are not correct: ' + str(e))
42+
raise MalformedRequestException(
43+
"Parameters for get_items request are not correct: " + str(e)
44+
)
4145

4246

4347
def get_items_response(amazon_api, request: GetItemsRequest) -> List[Item]:
@@ -47,20 +51,24 @@ def get_items_response(amazon_api, request: GetItemsRequest) -> List[Item]:
4751
_manage_response_exceptions(e)
4852

4953
if response.items_result == None:
50-
raise ItemsNotFoundException('No items have been found')
54+
raise ItemsNotFoundException("No items have been found")
5155

5256
return response.items_result.items
5357

5458

5559
def get_search_items_request(amazon_api, **kwargs) -> SearchItemsRequest:
5660
try:
57-
return SearchItemsRequest(resources=_get_request_resources(SearchItemsResource),
58-
partner_type=PartnerType.ASSOCIATES,
59-
marketplace=amazon_api._marketplace,
60-
partner_tag=amazon_api._tag,
61-
**kwargs)
61+
return SearchItemsRequest(
62+
resources=_get_request_resources(SearchItemsResource),
63+
partner_type=PartnerType.ASSOCIATES,
64+
marketplace=amazon_api._marketplace,
65+
partner_tag=amazon_api._tag,
66+
**kwargs
67+
)
6268
except TypeError as e:
63-
raise MalformedRequestException('Parameters for search_items request are not correct: ' + str(e))
69+
raise MalformedRequestException(
70+
"Parameters for search_items request are not correct: " + str(e)
71+
)
6472

6573

6674
def get_search_items_response(amazon_api, request: SearchItemsRequest) -> SearchResult:
@@ -70,74 +78,97 @@ def get_search_items_response(amazon_api, request: SearchItemsRequest) -> Search
7078
_manage_response_exceptions(e)
7179

7280
if response.search_result == None:
73-
raise ItemsNotFoundException('No items have been found')
81+
raise ItemsNotFoundException("No items have been found")
7482

7583
return response.search_result
7684

7785

7886
def get_variations_request(amazon_api, **kwargs) -> GetVariationsRequest:
7987
try:
80-
return GetVariationsRequest(resources=_get_request_resources(GetVariationsResource),
81-
partner_type=PartnerType.ASSOCIATES,
82-
marketplace=amazon_api._marketplace,
83-
partner_tag=amazon_api._tag,
84-
**kwargs)
88+
return GetVariationsRequest(
89+
resources=_get_request_resources(GetVariationsResource),
90+
partner_type=PartnerType.ASSOCIATES,
91+
marketplace=amazon_api._marketplace,
92+
partner_tag=amazon_api._tag,
93+
**kwargs
94+
)
8595
except TypeError as e:
86-
raise MalformedRequestException('Parameters for get_variations request are not correct: ' + str(e))
96+
raise MalformedRequestException(
97+
"Parameters for get_variations request are not correct: " + str(e)
98+
)
8799

88100

89-
def get_variations_response(amazon_api, request: GetVariationsRequest) -> VariationsResult:
101+
def get_variations_response(
102+
amazon_api, request: GetVariationsRequest
103+
) -> VariationsResult:
90104
try:
91105
response = amazon_api._api.get_variations(request)
92106
except ApiException as e:
93107
_manage_response_exceptions(e)
94108

95109
if response.variations_result == None:
96-
raise ItemsNotFoundException('No variation items have been found')
110+
raise ItemsNotFoundException("No variation items have been found")
97111

98112
return response.variations_result
99113

100114

101115
def get_browse_nodes_request(amazon_api, **kwargs) -> GetBrowseNodesRequest:
102116
try:
103-
return GetBrowseNodesRequest(resources=_get_request_resources(GetBrowseNodesResource),
104-
partner_type=PartnerType.ASSOCIATES,
105-
marketplace=amazon_api._marketplace,
106-
partner_tag=amazon_api._tag,
107-
**kwargs)
117+
return GetBrowseNodesRequest(
118+
resources=_get_request_resources(GetBrowseNodesResource),
119+
partner_type=PartnerType.ASSOCIATES,
120+
marketplace=amazon_api._marketplace,
121+
partner_tag=amazon_api._tag,
122+
**kwargs
123+
)
108124
except TypeError as e:
109-
raise MalformedRequestException('Parameters for get_browse_nodes request are not correct: ' + str(e))
125+
raise MalformedRequestException(
126+
"Parameters for get_browse_nodes request are not correct: " + str(e)
127+
)
110128

111129

112-
def get_browse_nodes_response(amazon_api, request: GetBrowseNodesRequest) -> List[BrowseNode]:
130+
def get_browse_nodes_response(
131+
amazon_api, request: GetBrowseNodesRequest
132+
) -> List[BrowseNode]:
113133
try:
114134
response = amazon_api._api.get_browse_nodes(request)
115135
except ApiException as e:
116136
_manage_response_exceptions(e)
117137

118138
if response.browse_nodes_result == None:
119-
raise ItemsNotFoundException('No browse nodes have been found')
139+
raise ItemsNotFoundException("No browse nodes have been found")
120140

121141
return response.browse_nodes_result.browse_nodes
122142

123143

124144
def _get_request_resources(resources) -> List[str]:
125-
resources = inspect.getmembers(resources, lambda a:not(inspect.isroutine(a)))
126-
resources = [x[-1] for x in resources if isinstance(x[-1], str) and x[0][0:2] != '__']
145+
resources = inspect.getmembers(resources, lambda a: not (inspect.isroutine(a)))
146+
resources = [
147+
x[-1] for x in resources if isinstance(x[-1], str) and x[0][0:2] != "__"
148+
]
127149
return resources
128150

151+
129152
def _manage_response_exceptions(error) -> None:
130153
if isinstance(error, ApiException):
131154
if error.status == 429:
132-
raise TooManyRequestsException('Requests limit reached, try increasing throttling or wait before trying again')
133-
134-
elif 'InvalidParameterValue' in error.body:
135-
raise InvalidArgumentException('The value provided in the request for atleast one parameter is invalid.')
136-
137-
elif 'InvalidPartnerTag' in error.body:
138-
raise InvalidArgumentException('The partner tag is invalid or not present.')
139-
140-
elif 'InvalidAssociate' in error.body:
141-
raise AssociateValidationException('Used credentials are not valid for the selected country.')
142-
143-
raise ApiRequestException('Request failed: ' + str(error.reason))
155+
raise TooManyRequestsException(
156+
"Requests limit reached, try increasing throttling or wait before"
157+
" trying again"
158+
)
159+
160+
elif "InvalidParameterValue" in error.body:
161+
raise InvalidArgumentException(
162+
"The value provided in the request for atleast one parameter is"
163+
" invalid."
164+
)
165+
166+
elif "InvalidPartnerTag" in error.body:
167+
raise InvalidArgumentException("The partner tag is invalid or not present.")
168+
169+
elif "InvalidAssociate" in error.body:
170+
raise AssociateValidationException(
171+
"Used credentials are not valid for the selected country."
172+
)
173+
174+
raise ApiRequestException("Request failed: " + str(error.reason))

0 commit comments

Comments
 (0)