python-amcards 1.7.6__tar.gz → 1.8.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {python_amcards-1.7.6/python_amcards.egg-info → python_amcards-1.8.0}/PKG-INFO +29 -1
- {python_amcards-1.7.6 → python_amcards-1.8.0}/README.rst +28 -0
- {python_amcards-1.7.6 → python_amcards-1.8.0}/amcards/amcards.py +120 -44
- {python_amcards-1.7.6 → python_amcards-1.8.0}/amcards/models.py +8 -0
- {python_amcards-1.7.6 → python_amcards-1.8.0/python_amcards.egg-info}/PKG-INFO +29 -1
- {python_amcards-1.7.6 → python_amcards-1.8.0}/python_amcards.egg-info/SOURCES.txt +4 -1
- {python_amcards-1.7.6 → python_amcards-1.8.0}/setup.py +1 -1
- python_amcards-1.8.0/tests/test_cards.py +64 -0
- python_amcards-1.8.0/tests/test_client.py +133 -0
- python_amcards-1.8.0/tests/test_user.py +21 -0
- {python_amcards-1.7.6 → python_amcards-1.8.0}/LICENSE +0 -0
- {python_amcards-1.7.6 → python_amcards-1.8.0}/amcards/__helpers.py +0 -0
- {python_amcards-1.7.6 → python_amcards-1.8.0}/amcards/__init__.py +0 -0
- {python_amcards-1.7.6 → python_amcards-1.8.0}/amcards/exceptions.py +0 -0
- {python_amcards-1.7.6 → python_amcards-1.8.0}/python_amcards.egg-info/dependency_links.txt +0 -0
- {python_amcards-1.7.6 → python_amcards-1.8.0}/python_amcards.egg-info/requires.txt +0 -0
- {python_amcards-1.7.6 → python_amcards-1.8.0}/python_amcards.egg-info/top_level.txt +0 -0
- {python_amcards-1.7.6 → python_amcards-1.8.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: python-amcards
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.8.0
|
|
4
4
|
Summary: A wrapper for the AMcards API.
|
|
5
5
|
Home-page: https://github.com/simonesestili/python-amcards
|
|
6
6
|
Author: Simone Sestili
|
|
@@ -81,3 +81,31 @@ Let's try using ``send_card`` to send a card to a single recipient:
|
|
|
81
81
|
{'last_name': 'Mullins', 'address_line_1': '2285 Reppert Road', 'first_name': 'Ralph', 'country': 'US', 'state': 'MI', 'postal_code': '48075', 'city': 'Southfield'}
|
|
82
82
|
|
|
83
83
|
The `AMcardsClient <https://python-amcards.readthedocs.io/en/latest/amcards.html#amcards.amcards.AMcardsClient>`_ supports many more operations, for full documentation see `Read the Docs <https://python-amcards.readthedocs.io/en/latest/>`_.
|
|
84
|
+
|
|
85
|
+
Request timeouts and tracking
|
|
86
|
+
-----------------------------
|
|
87
|
+
Configure a timeout once for every request, including OAuth token refreshes:
|
|
88
|
+
|
|
89
|
+
.. code-block:: python
|
|
90
|
+
|
|
91
|
+
client = AMcardsClient('youraccesstoken', timeout=(3, 6))
|
|
92
|
+
cards = client.cards(limit=1, filters={'third_party_contact_id': 'customer-123'})
|
|
93
|
+
tracking_number = cards[0].tracking_id if cards else None
|
|
94
|
+
|
|
95
|
+
The tuple means a 3-second connection timeout and a 6-second read timeout between
|
|
96
|
+
incoming data. It is not a total operation deadline. A single number applies to
|
|
97
|
+
both. The default is ``None``, preserving the previous behavior with no timeout.
|
|
98
|
+
Every API method accepts a ``timeout`` override; omitting it or passing ``None``
|
|
99
|
+
uses the client setting:
|
|
100
|
+
|
|
101
|
+
.. code-block:: python
|
|
102
|
+
|
|
103
|
+
cards = client.cards(limit=1, timeout=(3, 15))
|
|
104
|
+
|
|
105
|
+
Requests timeout exceptions propagate to the caller. The client does not retry
|
|
106
|
+
requests automatically; a timeout during a send does not establish whether the
|
|
107
|
+
server completed it.
|
|
108
|
+
|
|
109
|
+
``Card.tracking_id`` is ``None`` for absent or empty tracking identifiers.
|
|
110
|
+
Custom card metadata remains available through ``Card.extra_data``, and query
|
|
111
|
+
filters continue to use the existing ``filters`` dictionary.
|
|
@@ -55,3 +55,31 @@ Let's try using ``send_card`` to send a card to a single recipient:
|
|
|
55
55
|
{'last_name': 'Mullins', 'address_line_1': '2285 Reppert Road', 'first_name': 'Ralph', 'country': 'US', 'state': 'MI', 'postal_code': '48075', 'city': 'Southfield'}
|
|
56
56
|
|
|
57
57
|
The `AMcardsClient <https://python-amcards.readthedocs.io/en/latest/amcards.html#amcards.amcards.AMcardsClient>`_ supports many more operations, for full documentation see `Read the Docs <https://python-amcards.readthedocs.io/en/latest/>`_.
|
|
58
|
+
|
|
59
|
+
Request timeouts and tracking
|
|
60
|
+
-----------------------------
|
|
61
|
+
Configure a timeout once for every request, including OAuth token refreshes:
|
|
62
|
+
|
|
63
|
+
.. code-block:: python
|
|
64
|
+
|
|
65
|
+
client = AMcardsClient('youraccesstoken', timeout=(3, 6))
|
|
66
|
+
cards = client.cards(limit=1, filters={'third_party_contact_id': 'customer-123'})
|
|
67
|
+
tracking_number = cards[0].tracking_id if cards else None
|
|
68
|
+
|
|
69
|
+
The tuple means a 3-second connection timeout and a 6-second read timeout between
|
|
70
|
+
incoming data. It is not a total operation deadline. A single number applies to
|
|
71
|
+
both. The default is ``None``, preserving the previous behavior with no timeout.
|
|
72
|
+
Every API method accepts a ``timeout`` override; omitting it or passing ``None``
|
|
73
|
+
uses the client setting:
|
|
74
|
+
|
|
75
|
+
.. code-block:: python
|
|
76
|
+
|
|
77
|
+
cards = client.cards(limit=1, timeout=(3, 15))
|
|
78
|
+
|
|
79
|
+
Requests timeout exceptions propagate to the caller. The client does not retry
|
|
80
|
+
requests automatically; a timeout during a send does not establish whether the
|
|
81
|
+
server completed it.
|
|
82
|
+
|
|
83
|
+
``Card.tracking_id`` is ``None`` for absent or empty tracking identifiers.
|
|
84
|
+
Custom card metadata remains available through ``Card.extra_data``, and query
|
|
85
|
+
filters continue to use the existing ``filters`` dictionary.
|
|
@@ -8,6 +8,7 @@ from . import __helpers as helpers
|
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
DOMAIN = 'https://amcards.com'
|
|
11
|
+
Timeout = Optional[float | tuple[float, float]]
|
|
11
12
|
|
|
12
13
|
FIXED_COUNTRY = {
|
|
13
14
|
# US fixes
|
|
@@ -19,7 +20,7 @@ FIXED_COUNTRY = {
|
|
|
19
20
|
|
|
20
21
|
class AMcardsClient:
|
|
21
22
|
"""Client for AMcards API."""
|
|
22
|
-
def __init__(self, access_token: str, oauth_config: Optional[dict] = None, callback: Optional[Callable[[str, str, int], Any]] = None) -> None:
|
|
23
|
+
def __init__(self, access_token: str, oauth_config: Optional[dict] = None, callback: Optional[Callable[[str, str, int], Any]] = None, *, timeout: Timeout = None) -> None:
|
|
23
24
|
"""Client for AMcards API.
|
|
24
25
|
|
|
25
26
|
:param str access_token: Your AMcards access token. Generate one `here <https://amcards.com/user/generate-access-token/>`_.
|
|
@@ -36,15 +37,27 @@ class AMcardsClient:
|
|
|
36
37
|
|
|
37
38
|
:param Optional[Callable[[str, str, int], Any]] callback: This function will be called by the client when you have ``oauth_config`` defined, and the client refreshes the ``access_token`` before making a request. This can be useful when you need perform some logic when the client refreshes the specified ``access_token`` (like updating your database to reflect the new access_token and refresh_token). ``callback`` is optional, but if you choose to include it, it needs to accept the following keyword arguments: ``access_token`` ``refresh_token`` ``expiration``. ``callback`` will be called by the client as follows: ``callback(access_token='newaccesstoken', refresh_token='newrefreshtoken', expiration=1671692135130)``, note that ``expiration`` is specified as a unix timestamp in ms.
|
|
38
39
|
|
|
40
|
+
:param timeout: Timeout in seconds for every HTTP request, including OAuth refresh. Use a number for both connect/read timeouts, or a ``(connect, read)`` tuple. Defaults to ``None`` (no timeout). This is not a total operation deadline.
|
|
41
|
+
|
|
39
42
|
"""
|
|
40
43
|
self._access_token = access_token
|
|
41
44
|
self._oauth_config = oauth_config
|
|
42
45
|
self._callback = callback
|
|
46
|
+
self._timeout = timeout
|
|
47
|
+
|
|
48
|
+
def _request(self, method: str, url: str, *, timeout: Timeout = None, authenticated: bool = True, **kwargs) -> requests.Response:
|
|
49
|
+
"""Use the same timeout policy for all API calls and token refreshes."""
|
|
50
|
+
timeout = self._timeout if timeout is None else timeout
|
|
51
|
+
if authenticated:
|
|
52
|
+
if self._token_expired():
|
|
53
|
+
self._refresh_token(timeout=timeout)
|
|
54
|
+
kwargs['headers'] = {'Authorization': f'Bearer {self._access_token}'}
|
|
55
|
+
return requests.request(method, url, timeout=timeout, **kwargs)
|
|
43
56
|
|
|
44
57
|
def _token_expired(self) -> bool:
|
|
45
58
|
return self._oauth_config is not None and helpers.current_timestamp() >= self._oauth_config['expiration']
|
|
46
59
|
|
|
47
|
-
def _refresh_token(self) -> None:
|
|
60
|
+
def _refresh_token(self, *, timeout: Timeout = None) -> None:
|
|
48
61
|
# Refresh the tokens
|
|
49
62
|
payload = {
|
|
50
63
|
'grant_type': 'refresh_token',
|
|
@@ -52,7 +65,7 @@ class AMcardsClient:
|
|
|
52
65
|
'client_id': self._oauth_config['client_id'],
|
|
53
66
|
'client_secret': self._oauth_config['client_secret'],
|
|
54
67
|
}
|
|
55
|
-
res =
|
|
68
|
+
res = self._request('POST', url=f'{DOMAIN}/oauth2/token/', data=payload, timeout=timeout, authenticated=False)
|
|
56
69
|
|
|
57
70
|
# Make sure the refresh was successful
|
|
58
71
|
if not res.ok:
|
|
@@ -81,7 +94,7 @@ class AMcardsClient:
|
|
|
81
94
|
'Authorization': f'Bearer {self._access_token}',
|
|
82
95
|
}
|
|
83
96
|
|
|
84
|
-
def user(self) -> User:
|
|
97
|
+
def user(self, *, timeout: Timeout = None) -> User:
|
|
85
98
|
"""Fetches client's AMcards user.
|
|
86
99
|
|
|
87
100
|
:return: The client's :py:class:`user <amcards.models.User>`.
|
|
@@ -89,15 +102,17 @@ class AMcardsClient:
|
|
|
89
102
|
|
|
90
103
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
91
104
|
|
|
105
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
106
|
+
|
|
92
107
|
"""
|
|
93
|
-
res =
|
|
108
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/user/', timeout=timeout)
|
|
94
109
|
if not res.ok:
|
|
95
110
|
raise exceptions.AuthenticationError('Access token provided to client is unauthorized')
|
|
96
111
|
|
|
97
112
|
user_json = res.json().get('objects', [{}])[0]
|
|
98
113
|
return User._from_json(user_json)
|
|
99
114
|
|
|
100
|
-
def credit_transactions(self, limit: int = 25, skip: int = 0, filters: dict = None) -> List[CreditTransaction]:
|
|
115
|
+
def credit_transactions(self, limit: int = 25, skip: int = 0, filters: dict = None, *, timeout: Timeout = None) -> List[CreditTransaction]:
|
|
101
116
|
"""Fetches client's AMcards credit transactions.
|
|
102
117
|
|
|
103
118
|
:param int limit: Defaults to ``25``. Max number of credit transactions to be fetched.
|
|
@@ -111,13 +126,15 @@ class AMcardsClient:
|
|
|
111
126
|
|
|
112
127
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
113
128
|
|
|
129
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
130
|
+
|
|
114
131
|
"""
|
|
115
132
|
params = {
|
|
116
133
|
'limit': limit,
|
|
117
134
|
'offset': skip,
|
|
118
135
|
} | (filters or {})
|
|
119
136
|
|
|
120
|
-
res =
|
|
137
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/credittransaction/', params=params, timeout=timeout)
|
|
121
138
|
if not res.ok:
|
|
122
139
|
if res.status_code == 401:
|
|
123
140
|
raise exceptions.AuthenticationError('Access token provided to client is unauthorized')
|
|
@@ -126,7 +143,7 @@ class AMcardsClient:
|
|
|
126
143
|
credit_transactions_json = res.json().get('objects', [])
|
|
127
144
|
return [CreditTransaction._from_json(credit_transaction_json) for credit_transaction_json in credit_transactions_json]
|
|
128
145
|
|
|
129
|
-
def credit_transaction_count(self, filters: dict = None) -> int:
|
|
146
|
+
def credit_transaction_count(self, filters: dict = None, *, timeout: Timeout = None) -> int:
|
|
130
147
|
"""Fetches count of client's AMcards credit transactions.
|
|
131
148
|
|
|
132
149
|
:param Optional[dict] filters: Defaults to ``None``. Filters to be applied when counting credit transactions.
|
|
@@ -138,12 +155,14 @@ class AMcardsClient:
|
|
|
138
155
|
|
|
139
156
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
140
157
|
|
|
158
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
159
|
+
|
|
141
160
|
"""
|
|
142
161
|
params = {
|
|
143
162
|
'limit': 1,
|
|
144
163
|
} | (filters or {})
|
|
145
164
|
|
|
146
|
-
res =
|
|
165
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/credittransaction/', params=params, timeout=timeout)
|
|
147
166
|
if not res.ok:
|
|
148
167
|
if res.status_code == 401:
|
|
149
168
|
raise exceptions.AuthenticationError('Access token provided to client is unauthorized')
|
|
@@ -151,7 +170,7 @@ class AMcardsClient:
|
|
|
151
170
|
|
|
152
171
|
return res.json()['meta']['total_count']
|
|
153
172
|
|
|
154
|
-
def templates(self, limit: int = 25, skip: int = 0) -> List[Template]:
|
|
173
|
+
def templates(self, limit: int = 25, skip: int = 0, *, timeout: Timeout = None) -> List[Template]:
|
|
155
174
|
"""Fetches client's AMcards templates.
|
|
156
175
|
|
|
157
176
|
:param int limit: Defaults to ``25``. Max number of templates to be fetched.
|
|
@@ -162,8 +181,10 @@ class AMcardsClient:
|
|
|
162
181
|
|
|
163
182
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
164
183
|
|
|
184
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
185
|
+
|
|
165
186
|
"""
|
|
166
|
-
res =
|
|
187
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/template/', params={'limit': limit, 'offset': skip}, timeout=timeout)
|
|
167
188
|
if not res.ok:
|
|
168
189
|
if res.status_code == 401:
|
|
169
190
|
raise exceptions.AuthenticationError('Access token provided to client is unauthorized')
|
|
@@ -172,7 +193,7 @@ class AMcardsClient:
|
|
|
172
193
|
templates_json = res.json().get('objects', [])
|
|
173
194
|
return [Template._from_json(template_json) for template_json in templates_json]
|
|
174
195
|
|
|
175
|
-
def template(self, id: str | int) -> Template:
|
|
196
|
+
def template(self, id: str | int, *, timeout: Timeout = None) -> Template:
|
|
176
197
|
"""Fetches client's AMcards template with a specified id.
|
|
177
198
|
|
|
178
199
|
:param str or int id: Unique id for the :py:class:`template <amcards.models.Template>` you are fetching.
|
|
@@ -183,8 +204,10 @@ class AMcardsClient:
|
|
|
183
204
|
:raises ForbiddenTemplateError: When the template for the specified ``id`` either does not exist or is not owned by the client's user.
|
|
184
205
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
185
206
|
|
|
207
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
208
|
+
|
|
186
209
|
"""
|
|
187
|
-
res =
|
|
210
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/template/{id}/', timeout=timeout)
|
|
188
211
|
if not res.ok:
|
|
189
212
|
if res.status_code in (403, 404):
|
|
190
213
|
raise exceptions.ForbiddenTemplateError('The template for the specified id either does not exist or is not owned by the client\'s user')
|
|
@@ -193,7 +216,7 @@ class AMcardsClient:
|
|
|
193
216
|
template_json = res.json()
|
|
194
217
|
return Template._from_json(template_json)
|
|
195
218
|
|
|
196
|
-
def quicksends(self, limit: int = 25, skip: int = 0) -> List[Template]:
|
|
219
|
+
def quicksends(self, limit: int = 25, skip: int = 0, *, timeout: Timeout = None) -> List[Template]:
|
|
197
220
|
"""Fetches client's AMcards quicksend templates.
|
|
198
221
|
|
|
199
222
|
:param int limit: Defaults to ``25``. Max number of quicksend templates to be fetched.
|
|
@@ -204,8 +227,10 @@ class AMcardsClient:
|
|
|
204
227
|
|
|
205
228
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
206
229
|
|
|
230
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
231
|
+
|
|
207
232
|
"""
|
|
208
|
-
res =
|
|
233
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/quicksendtemplate/', params={'limit': limit, 'offset': skip}, timeout=timeout)
|
|
209
234
|
if not res.ok:
|
|
210
235
|
if res.status_code == 401:
|
|
211
236
|
raise exceptions.AuthenticationError('Access token provided to client is unauthorized')
|
|
@@ -214,7 +239,7 @@ class AMcardsClient:
|
|
|
214
239
|
templates_json = res.json().get('objects', [])
|
|
215
240
|
return [Template._from_json(template_json) for template_json in templates_json]
|
|
216
241
|
|
|
217
|
-
def quicksend(self, id: str | int) -> Template:
|
|
242
|
+
def quicksend(self, id: str | int, *, timeout: Timeout = None) -> Template:
|
|
218
243
|
"""Fetches client's AMcards quicksend template with a specified id.
|
|
219
244
|
|
|
220
245
|
:param str or int id: Unique id for the :py:class:`quicksend template <amcards.models.Template>` you are fetching.
|
|
@@ -225,8 +250,10 @@ class AMcardsClient:
|
|
|
225
250
|
:raises ForbiddenTemplateError: When the quicksend template for the specified ``id`` either does not exist or is not owned by the client's user.
|
|
226
251
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
227
252
|
|
|
253
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
254
|
+
|
|
228
255
|
"""
|
|
229
|
-
res =
|
|
256
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/quicksendtemplate/{id}/', timeout=timeout)
|
|
230
257
|
if not res.ok:
|
|
231
258
|
if res.status_code in (403, 404):
|
|
232
259
|
raise exceptions.ForbiddenTemplateError('The quicksend template for the specified id either does not exist or is not owned by the client\'s user')
|
|
@@ -235,7 +262,7 @@ class AMcardsClient:
|
|
|
235
262
|
template_json = res.json()
|
|
236
263
|
return Template._from_json(template_json)
|
|
237
264
|
|
|
238
|
-
def campaigns(self, limit: int = 25, skip: int = 0) -> List[Campaign]:
|
|
265
|
+
def campaigns(self, limit: int = 25, skip: int = 0, *, timeout: Timeout = None) -> List[Campaign]:
|
|
239
266
|
"""Fetches client's AMcards drip campaigns.
|
|
240
267
|
|
|
241
268
|
:param int limit: Defaults to ``25``. Max number of drip campaigns to be fetched.
|
|
@@ -246,8 +273,10 @@ class AMcardsClient:
|
|
|
246
273
|
|
|
247
274
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
248
275
|
|
|
276
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
277
|
+
|
|
249
278
|
"""
|
|
250
|
-
res =
|
|
279
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/campaign/', params={'limit': limit, 'offset': skip}, timeout=timeout)
|
|
251
280
|
if not res.ok:
|
|
252
281
|
if res.status_code == 401:
|
|
253
282
|
raise exceptions.AuthenticationError('Access token provided to client is unauthorized')
|
|
@@ -256,7 +285,7 @@ class AMcardsClient:
|
|
|
256
285
|
campaigns_json = res.json().get('objects', [])
|
|
257
286
|
return [Campaign._from_json(campaign_json) for campaign_json in campaigns_json]
|
|
258
287
|
|
|
259
|
-
def campaign(self, id: str | int) -> Campaign:
|
|
288
|
+
def campaign(self, id: str | int, *, timeout: Timeout = None) -> Campaign:
|
|
260
289
|
"""Fetches client's AMcards drip campaign with a specified id.
|
|
261
290
|
|
|
262
291
|
:param str or int id: Unique id for the :py:class:`drip campaign <amcards.models.Campaign>` you are fetching.
|
|
@@ -267,8 +296,10 @@ class AMcardsClient:
|
|
|
267
296
|
:raises ForbiddenCampaignError: When the drip campaign for the specified ``id`` either does not exist or is not owned by the client's user.
|
|
268
297
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
269
298
|
|
|
299
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
300
|
+
|
|
270
301
|
"""
|
|
271
|
-
res =
|
|
302
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/campaign/{id}/', timeout=timeout)
|
|
272
303
|
if not res.ok:
|
|
273
304
|
if res.status_code in (403, 404):
|
|
274
305
|
raise exceptions.ForbiddenCampaignError('The drip campaign for the specified id either does not exist or is not owned by the client\'s user')
|
|
@@ -277,7 +308,7 @@ class AMcardsClient:
|
|
|
277
308
|
campaign_json = res.json()
|
|
278
309
|
return Campaign._from_json(campaign_json)
|
|
279
310
|
|
|
280
|
-
def cards(self, limit: int = 25, skip: int = 0, filters: dict = None) -> List[Card]:
|
|
311
|
+
def cards(self, limit: int = 25, skip: int = 0, filters: dict = None, *, timeout: Timeout = None) -> List[Card]:
|
|
281
312
|
"""Fetches client's AMcards cards.
|
|
282
313
|
|
|
283
314
|
:param int limit: Defaults to ``25``. Max number of cards to be fetched.
|
|
@@ -291,22 +322,27 @@ class AMcardsClient:
|
|
|
291
322
|
|
|
292
323
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
293
324
|
|
|
325
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
326
|
+
|
|
294
327
|
"""
|
|
295
328
|
params = {
|
|
296
329
|
'limit': limit,
|
|
297
330
|
'offset': skip,
|
|
298
331
|
} | (filters or {})
|
|
299
332
|
|
|
300
|
-
res =
|
|
333
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/card/', params=params, timeout=timeout)
|
|
301
334
|
if not res.ok:
|
|
302
335
|
if res.status_code == 401:
|
|
303
336
|
raise exceptions.AuthenticationError('Access token provided to client is unauthorized')
|
|
304
337
|
raise exceptions.AMcardsException(f'Something went wrong when fetching cards. AMcards Status Code: {res.status_code}, AMcards Body: {res.text}.')
|
|
305
338
|
|
|
306
|
-
|
|
339
|
+
payload = res.json()
|
|
340
|
+
if not isinstance(payload, dict) or not isinstance(payload.get('objects'), list) or not isinstance(payload.get('meta'), dict) or 'next' not in payload['meta']:
|
|
341
|
+
raise exceptions.AMcardsException('Invalid card list response')
|
|
342
|
+
cards_json = payload['objects']
|
|
307
343
|
return [Card._from_json(card_json) for card_json in cards_json]
|
|
308
344
|
|
|
309
|
-
def card(self, id: str | int) -> Card:
|
|
345
|
+
def card(self, id: str | int, *, timeout: Timeout = None) -> Card:
|
|
310
346
|
"""Fetches client's AMcards card with a specified id.
|
|
311
347
|
|
|
312
348
|
:param str or int id: Unique id for the :py:class:`card <amcards.models.Card>` you are fetching.
|
|
@@ -317,8 +353,10 @@ class AMcardsClient:
|
|
|
317
353
|
:raises ForbiddenCardError: When the card for the specified ``id`` either does not exist or is not owned by the client's user.
|
|
318
354
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
319
355
|
|
|
356
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
357
|
+
|
|
320
358
|
"""
|
|
321
|
-
res =
|
|
359
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/card/{id}/', timeout=timeout)
|
|
322
360
|
if not res.ok:
|
|
323
361
|
if res.status_code in (403, 404):
|
|
324
362
|
raise exceptions.ForbiddenCardError('The card for the specified id either does not exist or is not owned by the client\'s user')
|
|
@@ -327,7 +365,7 @@ class AMcardsClient:
|
|
|
327
365
|
card_json = res.json()
|
|
328
366
|
return Card._from_json(card_json)
|
|
329
367
|
|
|
330
|
-
def card_count(self, filters: dict = None) -> int:
|
|
368
|
+
def card_count(self, filters: dict = None, *, timeout: Timeout = None) -> int:
|
|
331
369
|
"""Fetches count of client's AMcards cards.
|
|
332
370
|
|
|
333
371
|
:param Optional[dict] filters: Defaults to ``None``. Filters to be applied when counting cards.
|
|
@@ -339,12 +377,14 @@ class AMcardsClient:
|
|
|
339
377
|
|
|
340
378
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
341
379
|
|
|
380
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
381
|
+
|
|
342
382
|
"""
|
|
343
383
|
params = {
|
|
344
384
|
'limit': 1,
|
|
345
385
|
} | (filters or {})
|
|
346
386
|
|
|
347
|
-
res =
|
|
387
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/card/', params=params, timeout=timeout)
|
|
348
388
|
if not res.ok:
|
|
349
389
|
if res.status_code == 401:
|
|
350
390
|
raise exceptions.AuthenticationError('Access token provided to client is unauthorized')
|
|
@@ -352,7 +392,7 @@ class AMcardsClient:
|
|
|
352
392
|
|
|
353
393
|
return res.json()['meta']['total_count']
|
|
354
394
|
|
|
355
|
-
def mailing(self, id: str | int) -> Mailing:
|
|
395
|
+
def mailing(self, id: str | int, *, timeout: Timeout = None) -> Mailing:
|
|
356
396
|
"""Fetches client's AMcards mailing with a specified id.
|
|
357
397
|
|
|
358
398
|
:param str or int id: Unique id for the :py:class:`mailing <amcards.models.Mailing>` you are fetching.
|
|
@@ -363,8 +403,10 @@ class AMcardsClient:
|
|
|
363
403
|
:raises ForbiddenMailingError: When the mailing for the specified ``id`` either does not exist or is not owned by the client's user.
|
|
364
404
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
365
405
|
|
|
406
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
407
|
+
|
|
366
408
|
"""
|
|
367
|
-
res =
|
|
409
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/mailing/{id}/', timeout=timeout)
|
|
368
410
|
if not res.ok:
|
|
369
411
|
if res.status_code in (403, 404):
|
|
370
412
|
raise exceptions.ForbiddenMailingError('The mailing for the specified id either does not exist or is not owned by the client\'s user')
|
|
@@ -373,7 +415,7 @@ class AMcardsClient:
|
|
|
373
415
|
mailing_json = res.json()
|
|
374
416
|
return Mailing._from_json(mailing_json)
|
|
375
417
|
|
|
376
|
-
def contacts(self, limit: int = 25, skip: int = 0, filters: dict = None) -> List[Contact]:
|
|
418
|
+
def contacts(self, limit: int = 25, skip: int = 0, filters: dict = None, *, timeout: Timeout = None) -> List[Contact]:
|
|
377
419
|
"""Fetches client's AMcards contacts.
|
|
378
420
|
|
|
379
421
|
:param int limit: Defaults to ``25``. Max number of contacts to be fetched.
|
|
@@ -387,20 +429,22 @@ class AMcardsClient:
|
|
|
387
429
|
|
|
388
430
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
389
431
|
|
|
432
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
433
|
+
|
|
390
434
|
"""
|
|
391
435
|
params = {
|
|
392
436
|
'limit': limit,
|
|
393
437
|
'offset': skip,
|
|
394
438
|
} | (filters or {})
|
|
395
439
|
|
|
396
|
-
res =
|
|
440
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/contact/', params=params, timeout=timeout)
|
|
397
441
|
if not res.ok:
|
|
398
442
|
raise exceptions.AuthenticationError('Access token provided to client is unauthorized')
|
|
399
443
|
|
|
400
444
|
contacts_json = res.json().get('objects', [])
|
|
401
445
|
return [Contact._from_json(contact_json) for contact_json in contacts_json]
|
|
402
446
|
|
|
403
|
-
def contact(self, id: str | int) -> Contact:
|
|
447
|
+
def contact(self, id: str | int, *, timeout: Timeout = None) -> Contact:
|
|
404
448
|
"""Fetches client's AMcards contact with a specified id.
|
|
405
449
|
|
|
406
450
|
:param str or int id: Unique id for the :py:class:`contact <amcards.models.Contact>` you are fetching.
|
|
@@ -411,8 +455,10 @@ class AMcardsClient:
|
|
|
411
455
|
:raises ForbiddenContactError: When the contact for the specified ``id`` either does not exist or is not owned by the client's user.
|
|
412
456
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
413
457
|
|
|
458
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
459
|
+
|
|
414
460
|
"""
|
|
415
|
-
res =
|
|
461
|
+
res = self._request('GET', url=f'{DOMAIN}/.api/v1/contact/{id}/', timeout=timeout)
|
|
416
462
|
if not res.ok:
|
|
417
463
|
if res.status_code in (403, 404):
|
|
418
464
|
raise exceptions.ForbiddenContactError('The contact for the specified id either does not exist or is not owned by the client\'s user')
|
|
@@ -440,6 +486,8 @@ class AMcardsClient:
|
|
|
440
486
|
anniversary_year: Optional[str] = None,
|
|
441
487
|
anniversary_month: Optional[str] = None,
|
|
442
488
|
anniversary_day: Optional[str] = None,
|
|
489
|
+
*,
|
|
490
|
+
timeout: Timeout = None,
|
|
443
491
|
) -> None:
|
|
444
492
|
"""Creates a new contact for the client.
|
|
445
493
|
|
|
@@ -464,8 +512,10 @@ class AMcardsClient:
|
|
|
464
512
|
:raises AMcardsException: When something unexpected occurs.
|
|
465
513
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
466
514
|
|
|
515
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
516
|
+
|
|
467
517
|
"""
|
|
468
|
-
user_id = self.user().id
|
|
518
|
+
user_id = self.user(timeout=timeout).id
|
|
469
519
|
body = {
|
|
470
520
|
'first_name': first_name,
|
|
471
521
|
'last_name': last_name,
|
|
@@ -490,13 +540,13 @@ class AMcardsClient:
|
|
|
490
540
|
if anniversary_month is not None: body |= {'anniversary_month': anniversary_month}
|
|
491
541
|
if anniversary_day is not None: body |= {'anniversary_day': anniversary_day}
|
|
492
542
|
|
|
493
|
-
res =
|
|
543
|
+
res = self._request('POST', url=f'{DOMAIN}/.api/v1/contact/', json=body, timeout=timeout)
|
|
494
544
|
if not res.ok:
|
|
495
545
|
if res.status_code == 401:
|
|
496
546
|
raise exceptions.AuthenticationError('Access token provided to client is unauthorized')
|
|
497
547
|
raise exceptions.AMcardsException('Something went wrong when trying to create a contact')
|
|
498
548
|
|
|
499
|
-
def delete_contact(self, id: str | int) -> None:
|
|
549
|
+
def delete_contact(self, id: str | int, *, timeout: Timeout = None) -> None:
|
|
500
550
|
"""Deletes client's AMcards contact with a specified id.
|
|
501
551
|
|
|
502
552
|
:param str or int id: Unique id for the :py:class:`contact <amcards.models.Contact>` you are deleting.
|
|
@@ -504,8 +554,10 @@ class AMcardsClient:
|
|
|
504
554
|
:raises ForbiddenContactError: When the contact for the specified ``id`` either does not exist or is not owned by the client's user.
|
|
505
555
|
:raises AuthenticationError: When the client's ``access_token`` is invalid.
|
|
506
556
|
|
|
557
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
558
|
+
|
|
507
559
|
"""
|
|
508
|
-
res =
|
|
560
|
+
res = self._request('DELETE', url=f'{DOMAIN}/.api/v1/contact/{id}/', timeout=timeout)
|
|
509
561
|
if not res.ok:
|
|
510
562
|
if res.status_code in (403, 404):
|
|
511
563
|
raise exceptions.ForbiddenContactError('The contact for the specified id either does not exist or is not owned by the client\'s user')
|
|
@@ -517,6 +569,8 @@ class AMcardsClient:
|
|
|
517
569
|
shipping_address: dict,
|
|
518
570
|
return_address: dict = None,
|
|
519
571
|
send_date: str = None,
|
|
572
|
+
*,
|
|
573
|
+
timeout: Timeout = None,
|
|
520
574
|
) -> int:
|
|
521
575
|
"""Get cost for a card send. Without actually sending the card.
|
|
522
576
|
|
|
@@ -580,6 +634,8 @@ class AMcardsClient:
|
|
|
580
634
|
:raises ShippingAddressError: When ``shipping_address`` is missing some `required` keys.
|
|
581
635
|
:raises DateFormatError: When one of the dates provided is not in ``"YYYY-MM-DD"`` format.
|
|
582
636
|
|
|
637
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
638
|
+
|
|
583
639
|
"""
|
|
584
640
|
# Validate shipping address
|
|
585
641
|
missings = helpers.get_missing_required_shipping_address_fields(shipping_address)
|
|
@@ -599,7 +655,7 @@ class AMcardsClient:
|
|
|
599
655
|
# prefix return address fields with return_
|
|
600
656
|
return_address = {f'return_{key}': value for key, value in return_address.items()}
|
|
601
657
|
|
|
602
|
-
user = self.user()
|
|
658
|
+
user = self.user(timeout=timeout)
|
|
603
659
|
shipping_country = _fix_country(shipping_address['country'])
|
|
604
660
|
return_country = _fix_country(user.country)
|
|
605
661
|
if return_address is not None and 'return_country' in return_address:
|
|
@@ -620,6 +676,8 @@ class AMcardsClient:
|
|
|
620
676
|
send_date: str = None,
|
|
621
677
|
message: str = None,
|
|
622
678
|
extra_data: dict = None,
|
|
679
|
+
*,
|
|
680
|
+
timeout: Timeout = None,
|
|
623
681
|
) -> CardResponse:
|
|
624
682
|
"""Attempt to send a card.
|
|
625
683
|
|
|
@@ -704,6 +762,8 @@ class AMcardsClient:
|
|
|
704
762
|
:raises DateFormatError: When one of the dates provided is not in ``"YYYY-MM-DD"`` format.
|
|
705
763
|
:raises InsufficientCreditsError: When the client's user has insufficient credits in their balance.
|
|
706
764
|
|
|
765
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
766
|
+
|
|
707
767
|
"""
|
|
708
768
|
# Validate shipping address
|
|
709
769
|
missings = helpers.get_missing_required_shipping_address_fields(shipping_address)
|
|
@@ -744,7 +804,7 @@ class AMcardsClient:
|
|
|
744
804
|
if extra_data is not None:
|
|
745
805
|
body |= {'extra_data': extra_data}
|
|
746
806
|
|
|
747
|
-
res =
|
|
807
|
+
res = self._request('POST', f'{DOMAIN}/cards/open-card-form-oa/', json=body, timeout=timeout)
|
|
748
808
|
|
|
749
809
|
# Check for errors
|
|
750
810
|
match res.status_code:
|
|
@@ -768,6 +828,8 @@ class AMcardsClient:
|
|
|
768
828
|
shipping_address: dict,
|
|
769
829
|
return_address: dict = None,
|
|
770
830
|
send_date: str = None,
|
|
831
|
+
*,
|
|
832
|
+
timeout: Timeout = None,
|
|
771
833
|
) -> int:
|
|
772
834
|
"""Get cost for a campaign send. Without actually sending the campaign.
|
|
773
835
|
|
|
@@ -835,6 +897,8 @@ class AMcardsClient:
|
|
|
835
897
|
:raises DateFormatError: When one of the dates provided is not in ``"YYYY-MM-DD"`` format.
|
|
836
898
|
:raises PhoneFormatError: When the ``phone_number`` is not a digit string of length 10.
|
|
837
899
|
|
|
900
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
901
|
+
|
|
838
902
|
"""
|
|
839
903
|
# Validate shipping address
|
|
840
904
|
missings = helpers.get_missing_required_shipping_address_fields(shipping_address)
|
|
@@ -883,7 +947,7 @@ class AMcardsClient:
|
|
|
883
947
|
body['recipients'][0]['birth_day'] = shipping_address['birth_date'][-2:]
|
|
884
948
|
body['recipients'][0]['birth_month'] = shipping_address['birth_date'][-5:-3]
|
|
885
949
|
|
|
886
|
-
res =
|
|
950
|
+
res = self._request('POST', f'{DOMAIN}/campaigns/calculate-campaign-price/', json=body, timeout=timeout)
|
|
887
951
|
|
|
888
952
|
# Check for errors
|
|
889
953
|
match res.status_code:
|
|
@@ -903,6 +967,8 @@ class AMcardsClient:
|
|
|
903
967
|
send_date: str = None,
|
|
904
968
|
extra_data: dict = None,
|
|
905
969
|
bypass_duplicate_check: bool = False,
|
|
970
|
+
*,
|
|
971
|
+
timeout: Timeout = None,
|
|
906
972
|
) -> CampaignResponse:
|
|
907
973
|
"""Attempt to send a drip campaign.
|
|
908
974
|
|
|
@@ -992,6 +1058,8 @@ class AMcardsClient:
|
|
|
992
1058
|
:raises InsufficientCreditsError: When the client's user has insufficient credits in their balance.
|
|
993
1059
|
:raises DuplicateCampaignError: When AMcards detects this :py:class:`campaign <amcards.models.Campaign>` specified by ``campaign_id`` is a duplicate and ``send_if_duplicate`` in :py:class:`Campaign <amcards.models.Campaign>` is ``False``.
|
|
994
1060
|
|
|
1061
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
1062
|
+
|
|
995
1063
|
"""
|
|
996
1064
|
# Validate shipping address
|
|
997
1065
|
missings = helpers.get_missing_required_shipping_address_fields(shipping_address)
|
|
@@ -1044,7 +1112,7 @@ class AMcardsClient:
|
|
|
1044
1112
|
if bypass_duplicate_check:
|
|
1045
1113
|
body |= {'bypass_duplicate_check': True}
|
|
1046
1114
|
|
|
1047
|
-
res =
|
|
1115
|
+
res = self._request('POST', f'{DOMAIN}/campaigns/open-campaign-form/', json=body, timeout=timeout)
|
|
1048
1116
|
|
|
1049
1117
|
# Check for errors
|
|
1050
1118
|
match res.status_code:
|
|
@@ -1069,6 +1137,8 @@ class AMcardsClient:
|
|
|
1069
1137
|
campaign_id: str | int,
|
|
1070
1138
|
initiator: str,
|
|
1071
1139
|
contacts: List[dict],
|
|
1140
|
+
*,
|
|
1141
|
+
timeout: Timeout = None,
|
|
1072
1142
|
) -> CampaignMultiResponse:
|
|
1073
1143
|
"""Attempt to send a drip campaign to multiple contacts.
|
|
1074
1144
|
|
|
@@ -1144,6 +1214,8 @@ class AMcardsClient:
|
|
|
1144
1214
|
:raises ShippingAddressError: When none of the provided contacts are valid after validation. Contacts missing required fields or with invalid optional fields are skipped.
|
|
1145
1215
|
:raises InsufficientCreditsError: When the client's user has insufficient credits in their balance.
|
|
1146
1216
|
|
|
1217
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
1218
|
+
|
|
1147
1219
|
"""
|
|
1148
1220
|
contacts_to_send = []
|
|
1149
1221
|
|
|
@@ -1181,7 +1253,7 @@ class AMcardsClient:
|
|
|
1181
1253
|
'contacts': valid_contacts,
|
|
1182
1254
|
}
|
|
1183
1255
|
|
|
1184
|
-
res =
|
|
1256
|
+
res = self._request('POST', f'{DOMAIN}/campaigns/open-campaign-multi-form/', json=body, timeout=timeout)
|
|
1185
1257
|
|
|
1186
1258
|
# Check for errors
|
|
1187
1259
|
match res.status_code:
|
|
@@ -1203,6 +1275,8 @@ class AMcardsClient:
|
|
|
1203
1275
|
return_address: dict = None,
|
|
1204
1276
|
send_date: str = None,
|
|
1205
1277
|
send_if_error: bool = False,
|
|
1278
|
+
*,
|
|
1279
|
+
timeout: Timeout = None,
|
|
1206
1280
|
) -> CardsResponse:
|
|
1207
1281
|
"""Attempt to send multiple cards.
|
|
1208
1282
|
|
|
@@ -1302,6 +1376,8 @@ class AMcardsClient:
|
|
|
1302
1376
|
:raises DateFormatError: When one of the dates provided is not in ``"YYYY-MM-DD"`` format.
|
|
1303
1377
|
:raises InsufficientCreditsError: When the client's user has insufficient credits in their balance.
|
|
1304
1378
|
|
|
1379
|
+
:param timeout: Optional connect/read timeout override for this operation. ``None`` uses the client timeout.
|
|
1380
|
+
|
|
1305
1381
|
"""
|
|
1306
1382
|
# Validate shipping addresses
|
|
1307
1383
|
for idx, shipping_address in enumerate(shipping_addresses):
|
|
@@ -1340,7 +1416,7 @@ class AMcardsClient:
|
|
|
1340
1416
|
if send_date is not None:
|
|
1341
1417
|
body |= {'send_type': 'specific_date', 'send_date': send_date}
|
|
1342
1418
|
|
|
1343
|
-
res =
|
|
1419
|
+
res = self._request('POST', f'{DOMAIN}/cards/open-mailing-form/', json=body, timeout=timeout)
|
|
1344
1420
|
|
|
1345
1421
|
# Check for errors
|
|
1346
1422
|
match res.status_code:
|
|
@@ -384,6 +384,7 @@ class Card:
|
|
|
384
384
|
return_address: dict,
|
|
385
385
|
gifts: List[Gift],
|
|
386
386
|
extra_data: dict,
|
|
387
|
+
tracking_id: Optional[str] = None,
|
|
387
388
|
) -> None:
|
|
388
389
|
self._id = id
|
|
389
390
|
self._amount_charged = amount_charged
|
|
@@ -402,6 +403,7 @@ class Card:
|
|
|
402
403
|
self._return_address = return_address
|
|
403
404
|
self._gifts = gifts
|
|
404
405
|
self._extra_data = extra_data
|
|
406
|
+
self._tracking_id = tracking_id
|
|
405
407
|
|
|
406
408
|
__repr__ = helpers.repr
|
|
407
409
|
|
|
@@ -532,6 +534,11 @@ class Card:
|
|
|
532
534
|
"""Extra data attached to this card."""
|
|
533
535
|
return self._extra_data
|
|
534
536
|
|
|
537
|
+
@property
|
|
538
|
+
def tracking_id(self) -> Optional[str]:
|
|
539
|
+
"""Shipment tracking identifier, or ``None`` when none is available."""
|
|
540
|
+
return self._tracking_id
|
|
541
|
+
|
|
535
542
|
@classmethod
|
|
536
543
|
def _from_json(cls, json: dict):
|
|
537
544
|
return cls(
|
|
@@ -557,6 +564,7 @@ class Card:
|
|
|
557
564
|
shipping_and_handling_cost=gift['shipping_and_handling'],
|
|
558
565
|
) for gift in json['gifts']],
|
|
559
566
|
extra_data=ast.literal_eval(json.get('extra_data') or '{}'),
|
|
567
|
+
tracking_id=json.get('tracking_id') or None,
|
|
560
568
|
)
|
|
561
569
|
|
|
562
570
|
class MailingStatus(Enum):
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: python-amcards
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.8.0
|
|
4
4
|
Summary: A wrapper for the AMcards API.
|
|
5
5
|
Home-page: https://github.com/simonesestili/python-amcards
|
|
6
6
|
Author: Simone Sestili
|
|
@@ -81,3 +81,31 @@ Let's try using ``send_card`` to send a card to a single recipient:
|
|
|
81
81
|
{'last_name': 'Mullins', 'address_line_1': '2285 Reppert Road', 'first_name': 'Ralph', 'country': 'US', 'state': 'MI', 'postal_code': '48075', 'city': 'Southfield'}
|
|
82
82
|
|
|
83
83
|
The `AMcardsClient <https://python-amcards.readthedocs.io/en/latest/amcards.html#amcards.amcards.AMcardsClient>`_ supports many more operations, for full documentation see `Read the Docs <https://python-amcards.readthedocs.io/en/latest/>`_.
|
|
84
|
+
|
|
85
|
+
Request timeouts and tracking
|
|
86
|
+
-----------------------------
|
|
87
|
+
Configure a timeout once for every request, including OAuth token refreshes:
|
|
88
|
+
|
|
89
|
+
.. code-block:: python
|
|
90
|
+
|
|
91
|
+
client = AMcardsClient('youraccesstoken', timeout=(3, 6))
|
|
92
|
+
cards = client.cards(limit=1, filters={'third_party_contact_id': 'customer-123'})
|
|
93
|
+
tracking_number = cards[0].tracking_id if cards else None
|
|
94
|
+
|
|
95
|
+
The tuple means a 3-second connection timeout and a 6-second read timeout between
|
|
96
|
+
incoming data. It is not a total operation deadline. A single number applies to
|
|
97
|
+
both. The default is ``None``, preserving the previous behavior with no timeout.
|
|
98
|
+
Every API method accepts a ``timeout`` override; omitting it or passing ``None``
|
|
99
|
+
uses the client setting:
|
|
100
|
+
|
|
101
|
+
.. code-block:: python
|
|
102
|
+
|
|
103
|
+
cards = client.cards(limit=1, timeout=(3, 15))
|
|
104
|
+
|
|
105
|
+
Requests timeout exceptions propagate to the caller. The client does not retry
|
|
106
|
+
requests automatically; a timeout during a send does not establish whether the
|
|
107
|
+
server completed it.
|
|
108
|
+
|
|
109
|
+
``Card.tracking_id`` is ``None`` for absent or empty tracking identifiers.
|
|
110
|
+
Custom card metadata remains available through ``Card.extra_data``, and query
|
|
111
|
+
filters continue to use the existing ``filters`` dictionary.
|
|
@@ -10,4 +10,7 @@ python_amcards.egg-info/PKG-INFO
|
|
|
10
10
|
python_amcards.egg-info/SOURCES.txt
|
|
11
11
|
python_amcards.egg-info/dependency_links.txt
|
|
12
12
|
python_amcards.egg-info/requires.txt
|
|
13
|
-
python_amcards.egg-info/top_level.txt
|
|
13
|
+
python_amcards.egg-info/top_level.txt
|
|
14
|
+
tests/test_cards.py
|
|
15
|
+
tests/test_client.py
|
|
16
|
+
tests/test_user.py
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
from unittest.mock import Mock, patch
|
|
3
|
+
|
|
4
|
+
from amcards import AMcardsClient
|
|
5
|
+
from amcards.exceptions import AMcardsException
|
|
6
|
+
from amcards.models import Card
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
CARD = {
|
|
10
|
+
'id': 1,
|
|
11
|
+
'amount_charged': 1.25,
|
|
12
|
+
'status': 0,
|
|
13
|
+
'initiator': 'test',
|
|
14
|
+
'send_date': '2026-11-22',
|
|
15
|
+
'created': '2026-11-21T10:00:00',
|
|
16
|
+
'last_modified': None,
|
|
17
|
+
'fulfilled': None,
|
|
18
|
+
'is_international': False,
|
|
19
|
+
'template_name': 'Example',
|
|
20
|
+
'thumbnail': '',
|
|
21
|
+
'campaign_pk': 1,
|
|
22
|
+
'third_party_contact_id': 'customer',
|
|
23
|
+
'gifts': [],
|
|
24
|
+
'extra_data': "{'custom_field': 'value'}",
|
|
25
|
+
'tracking_id': 'test-tracking',
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def response(payload, status=200):
|
|
30
|
+
return Mock(ok=status < 400, status_code=status, json=lambda: payload, text='test response')
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class CardTests(unittest.TestCase):
|
|
34
|
+
def test_list_and_detail_expose_tracking_and_custom_metadata(self):
|
|
35
|
+
for method in ('cards', 'card'):
|
|
36
|
+
with self.subTest(method=method):
|
|
37
|
+
payload = {'objects': [CARD], 'meta': {'next': None}} if method == 'cards' else CARD
|
|
38
|
+
with patch('amcards.amcards.requests.request', return_value=response(payload)):
|
|
39
|
+
result = getattr(AMcardsClient('test'), method)(1)
|
|
40
|
+
card = result[0] if method == 'cards' else result
|
|
41
|
+
self.assertEqual(card.tracking_id, 'test-tracking')
|
|
42
|
+
self.assertEqual(card.extra_data, {'custom_field': 'value'})
|
|
43
|
+
self.assertEqual(card.shipping_address['third_party_contact_id'], 'customer')
|
|
44
|
+
|
|
45
|
+
def test_absent_null_and_empty_tracking_are_optional(self):
|
|
46
|
+
without_tracking = {key: value for key, value in CARD.items() if key != 'tracking_id'}
|
|
47
|
+
for payload in (without_tracking, CARD | {'tracking_id': None}, CARD | {'tracking_id': ''}):
|
|
48
|
+
with self.subTest(payload=payload.get('tracking_id', 'absent')):
|
|
49
|
+
self.assertIsNone(Card._from_json(payload).tracking_id)
|
|
50
|
+
|
|
51
|
+
def test_old_card_constructor_remains_compatible(self):
|
|
52
|
+
card = Card(1, 100, 100, 0, 'test', '2026-11-22', None, None, None, False, 'Example', '', None, {}, {}, [], {})
|
|
53
|
+
self.assertIsNone(card.tracking_id)
|
|
54
|
+
|
|
55
|
+
def test_malformed_card_list_is_not_an_empty_result(self):
|
|
56
|
+
for payload in ({}, [], {'objects': []}, {'objects': None, 'meta': {'next': None}}, {'objects': [], 'meta': {}}):
|
|
57
|
+
with self.subTest(payload=payload):
|
|
58
|
+
with patch('amcards.amcards.requests.request', return_value=response(payload)):
|
|
59
|
+
with self.assertRaises(AMcardsException):
|
|
60
|
+
AMcardsClient('test').cards()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
if __name__ == '__main__':
|
|
64
|
+
unittest.main()
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import unittest
|
|
3
|
+
from unittest.mock import Mock, patch
|
|
4
|
+
|
|
5
|
+
import requests
|
|
6
|
+
|
|
7
|
+
from amcards import AMcardsClient
|
|
8
|
+
from amcards.exceptions import AMcardsException, AuthenticationError, OAuthTokenRefreshError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
ADDRESS = {
|
|
12
|
+
'first_name': 'Test',
|
|
13
|
+
'last_name': 'Customer',
|
|
14
|
+
'address_line_1': '1 Example Street',
|
|
15
|
+
'city': 'Example',
|
|
16
|
+
'state': 'CA',
|
|
17
|
+
'postal_code': '90001',
|
|
18
|
+
'country': 'US',
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def response(payload, status=200):
|
|
23
|
+
return Mock(ok=status < 400, status_code=status, json=lambda: payload, text='test response')
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ClientTimeoutTests(unittest.TestCase):
|
|
27
|
+
def test_all_operations_inherit_and_override_timeouts_without_retrying(self):
|
|
28
|
+
operations = {
|
|
29
|
+
'user': {},
|
|
30
|
+
'credit_transactions': {},
|
|
31
|
+
'credit_transaction_count': {},
|
|
32
|
+
'templates': {},
|
|
33
|
+
'template': {'id': 1},
|
|
34
|
+
'quicksends': {},
|
|
35
|
+
'quicksend': {'id': 1},
|
|
36
|
+
'campaigns': {},
|
|
37
|
+
'campaign': {'id': 1},
|
|
38
|
+
'cards': {},
|
|
39
|
+
'card': {'id': 1},
|
|
40
|
+
'card_count': {},
|
|
41
|
+
'mailing': {'id': 1},
|
|
42
|
+
'contacts': {},
|
|
43
|
+
'contact': {'id': 1},
|
|
44
|
+
'create_contact': ADDRESS,
|
|
45
|
+
'delete_contact': {'id': 1},
|
|
46
|
+
'send_card_cost': {'template_id': 1, 'shipping_address': ADDRESS},
|
|
47
|
+
'send_card': {'template_id': 1, 'shipping_address': ADDRESS, 'initiator': 'test'},
|
|
48
|
+
'send_campaign_cost': {'campaign_id': 1, 'shipping_address': ADDRESS},
|
|
49
|
+
'send_campaign': {'campaign_id': 1, 'shipping_address': ADDRESS, 'initiator': 'test'},
|
|
50
|
+
'send_campaign_multi': {'campaign_id': 1, 'contacts': [ADDRESS], 'initiator': 'test'},
|
|
51
|
+
'send_cards': {'template_id': 1, 'shipping_addresses': [ADDRESS], 'initiator': 'test'},
|
|
52
|
+
}
|
|
53
|
+
for name, arguments in operations.items():
|
|
54
|
+
for default, override in ((None, None), ((3, 6), None), ((3, 6), 9), (5, (1, 2))):
|
|
55
|
+
with self.subTest(operation=name, default=default, override=override):
|
|
56
|
+
client = AMcardsClient('test-token', timeout=default)
|
|
57
|
+
with patch('amcards.amcards.requests.request', side_effect=requests.ReadTimeout) as request:
|
|
58
|
+
with self.assertRaises(requests.ReadTimeout):
|
|
59
|
+
getattr(client, name)(**copy.deepcopy(arguments), timeout=override)
|
|
60
|
+
request.assert_called_once()
|
|
61
|
+
self.assertEqual(request.call_args.kwargs['timeout'], default if override is None else override)
|
|
62
|
+
self.assertEqual(request.call_args.kwargs['headers'], {'Authorization': 'Bearer test-token'})
|
|
63
|
+
|
|
64
|
+
def test_override_does_not_change_default_or_query_parameters(self):
|
|
65
|
+
client = AMcardsClient('test-token', timeout=(3, 6))
|
|
66
|
+
filters = {'third_party_contact_id': 'customer', 'order_by': ['-send_date', '-id']}
|
|
67
|
+
with patch('amcards.amcards.requests.request', return_value=response({'objects': [], 'meta': {'next': None}})) as request:
|
|
68
|
+
self.assertEqual(client.cards(1, 5, filters, timeout=2), [])
|
|
69
|
+
self.assertEqual(request.call_args.kwargs['params'], {'limit': 1, 'offset': 5, **filters})
|
|
70
|
+
self.assertEqual(request.call_args.kwargs['timeout'], 2)
|
|
71
|
+
client.cards()
|
|
72
|
+
self.assertEqual(request.call_args.kwargs['timeout'], (3, 6))
|
|
73
|
+
self.assertNotIn('timeout', filters)
|
|
74
|
+
|
|
75
|
+
def test_oauth_refresh_uses_effective_timeout_and_new_token(self):
|
|
76
|
+
for override in (None, (1, 2)):
|
|
77
|
+
with self.subTest(override=override):
|
|
78
|
+
callback = Mock()
|
|
79
|
+
config = {'refresh_token': 'old-refresh', 'expiration': 0, 'client_id': 'test-id', 'client_secret': 'test-secret'}
|
|
80
|
+
client = AMcardsClient('old-token', config, callback, timeout=(3, 6))
|
|
81
|
+
responses = [
|
|
82
|
+
response({'access_token': 'new-token', 'refresh_token': 'new-refresh', 'expires_in': 60}),
|
|
83
|
+
response({'objects': [], 'meta': {'next': None}}),
|
|
84
|
+
]
|
|
85
|
+
with patch('amcards.amcards.requests.request', side_effect=responses) as request, patch('amcards.amcards.helpers.current_timestamp', return_value=1000):
|
|
86
|
+
client.cards(timeout=override)
|
|
87
|
+
refresh, api = request.call_args_list
|
|
88
|
+
expected = override or (3, 6)
|
|
89
|
+
self.assertEqual(refresh.args[0], 'POST')
|
|
90
|
+
self.assertTrue(refresh.args[1].endswith('/oauth2/token/'))
|
|
91
|
+
self.assertNotIn('headers', refresh.kwargs)
|
|
92
|
+
self.assertEqual(refresh.kwargs['timeout'], expected)
|
|
93
|
+
self.assertEqual(api.kwargs['timeout'], expected)
|
|
94
|
+
self.assertEqual(api.kwargs['headers'], {'Authorization': 'Bearer new-token'})
|
|
95
|
+
callback.assert_called_once_with(access_token='new-token', refresh_token='new-refresh', expiration=61000)
|
|
96
|
+
|
|
97
|
+
def test_failed_or_timed_out_refresh_does_not_make_api_call(self):
|
|
98
|
+
for failure in (response({}, 400), requests.ConnectTimeout()):
|
|
99
|
+
with self.subTest(failure=type(failure).__name__):
|
|
100
|
+
client = AMcardsClient('old-token', {'refresh_token': 'test', 'expiration': 0, 'client_id': 'test', 'client_secret': 'test'}, timeout=3)
|
|
101
|
+
with patch('amcards.amcards.requests.request', side_effect=[failure]) as request:
|
|
102
|
+
with self.assertRaises((OAuthTokenRefreshError, requests.ConnectTimeout)):
|
|
103
|
+
client.cards()
|
|
104
|
+
request.assert_called_once()
|
|
105
|
+
|
|
106
|
+
def test_default_without_timeout_remains_compatible(self):
|
|
107
|
+
with patch('amcards.amcards.requests.request', return_value=response({'meta': {'total_count': 5}})) as request:
|
|
108
|
+
self.assertEqual(AMcardsClient('test-token', None, None).card_count(), 5)
|
|
109
|
+
self.assertIsNone(request.call_args.kwargs['timeout'])
|
|
110
|
+
|
|
111
|
+
def test_contact_creation_override_covers_user_lookup_and_write(self):
|
|
112
|
+
client = AMcardsClient('test-token', timeout=30)
|
|
113
|
+
with patch('amcards.amcards.requests.request', side_effect=[response({'objects': [{}]}), requests.ReadTimeout()]) as request:
|
|
114
|
+
with patch('amcards.models.User._from_json', return_value=Mock(id=123)):
|
|
115
|
+
with self.assertRaises(requests.ReadTimeout):
|
|
116
|
+
client.create_contact(**ADDRESS, timeout=(2, 4))
|
|
117
|
+
lookup, create = request.call_args_list
|
|
118
|
+
self.assertEqual(lookup.args[0], 'GET')
|
|
119
|
+
self.assertEqual(create.args[0], 'POST')
|
|
120
|
+
self.assertEqual(lookup.kwargs['timeout'], (2, 4))
|
|
121
|
+
self.assertEqual(create.kwargs['timeout'], (2, 4))
|
|
122
|
+
self.assertEqual(create.kwargs['json']['first_name'], 'Test')
|
|
123
|
+
|
|
124
|
+
def test_sdk_errors_remain_sdk_errors(self):
|
|
125
|
+
for status, expected in ((401, AuthenticationError), (503, AMcardsException)):
|
|
126
|
+
with self.subTest(status=status):
|
|
127
|
+
with patch('amcards.amcards.requests.request', return_value=response({}, status)):
|
|
128
|
+
with self.assertRaises(expected):
|
|
129
|
+
AMcardsClient('test').cards()
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
if __name__ == '__main__':
|
|
133
|
+
unittest.main()
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
|
|
3
|
+
from amcards.models import User
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class UserTests(unittest.TestCase):
|
|
7
|
+
def test_published_monthly_report_emails_are_preserved(self):
|
|
8
|
+
payload = {
|
|
9
|
+
'resource_uri': '/.api/v1/user/1/',
|
|
10
|
+
'first_name': 'Test', 'last_name': 'User', 'credits': 0, 'email': 'test@example.com', 'phone': '',
|
|
11
|
+
'date_joined': '2026-11-21T10:00:00', 'address_line_1': '', 'city': '', 'state': '', 'postal': '', 'country': 'US',
|
|
12
|
+
'postage': {'domestic_cost': 0, 'international_cost': 0, 'domestic_countries': ['US']},
|
|
13
|
+
'product_pricing_info': {'5x7greetingcard': 0},
|
|
14
|
+
}
|
|
15
|
+
for emails in (None, [], ['reports@example.com']):
|
|
16
|
+
with self.subTest(emails=emails):
|
|
17
|
+
self.assertEqual(User._from_json(payload | {'monthly_report_emails': emails}).monthly_report_emails, emails or [])
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
if __name__ == '__main__':
|
|
21
|
+
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|