Skip to content

Commit 4fdea7a

Browse files
🌎 azure-na support
1 parent ab4784e commit 4fdea7a

File tree

14 files changed

+92
-95
lines changed

14 files changed

+92
-95
lines changed

contentstack/assetquery.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,10 @@ def __init__(self, http_instance):
2424
super().__init__()
2525
self.http_instance = http_instance
2626
self.asset_query_params = {}
27-
self.base_url = "{}/assets".format(self.http_instance.endpoint)
27+
self.base_url = f"{self.http_instance.endpoint}/assets"
2828
if "environment" in self.http_instance.headers:
2929
env = self.http_instance.headers["environment"]
30-
self.base_url = "{}?{}".format(
31-
self.base_url, "environment={}".format(env))
30+
self.base_url = f"{self.base_url}?environment={env}"
3231

3332
def environment(self, environment):
3433
r"""Provide the name of the environment if you wish to retrieve the assets published

contentstack/basequery.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
import enum
32
import logging
43

contentstack/contenttype.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
# ************* Module ContentType **************
99
# Your code has been rated at 10.00/10 by pylint
10-
10+
import json
1111
import logging
1212
from urllib import parse
1313

@@ -43,13 +43,15 @@ def entry(self, entry_uid: str):
4343
>>> import contentstack
4444
>>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
4545
>>> content_type = stack.content_type('content_type_uid')
46-
>>> entry = content_type.entry(uid='entry_uid')
46+
>>> content_type.entry(uid='entry_uid')
4747
--------------------------------
4848
"""
4949
if self.__content_type_uid is None:
5050
raise PermissionError('Please provide valid content_type_uid')
5151
if entry_uid is None:
52-
raise PermissionError('Please provide valid entry uid')
52+
raise PermissionError(json.dumps({
53+
"message": 'Please provide valid entry uid',
54+
"message_detail": 'Entry UID can not be None'}))
5355
entry = Entry(self.http_instance,
5456
self.__content_type_uid, entry_uid=entry_uid)
5557
return entry

contentstack/entry.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55

66
import logging
77
from urllib import parse
8+
9+
import empty as empty
10+
811
from contentstack.entryqueryable import EntryQueryable
912

1013
# ************* Module Entry **************
@@ -157,13 +160,12 @@ def include_embedded_items(self):
157160
return self
158161

159162
def __get_base_url(self, endpoint=''):
160-
if endpoint is not None and not endpoint.empty:
163+
if endpoint is not None and not empty:
161164
self.http_instance.endpoint = endpoint
162165
if None in (self.http_instance, self.content_type_id, self.entry_uid):
163166
raise KeyError(
164167
'Provide valid http_instance, content_type_uid or entry_uid')
165-
url = '{}/content_types/{}/entries/{}' \
166-
.format(self.http_instance.endpoint, self.content_type_id, self.entry_uid)
168+
url = f'{self.http_instance.endpoint}/content_types/{self.content_type_id}/entries/{self.entry_uid}'
167169
return url
168170

169171
def __validate_live_preview(self):
@@ -195,5 +197,5 @@ def fetch(self):
195197
if len(self.entry_queryable_param) > 0:
196198
self.entry_param.update(self.entry_queryable_param)
197199
encoded_string = parse.urlencode(self.entry_param, doseq=True)
198-
url = '{}?{}'.format(self.base_url, encoded_string)
200+
url = f'{self.base_url}?{encoded_string}'
199201
return self.http_instance.get(url)

contentstack/entryqueryable.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,11 @@ def __init__(self):
2020

2121
def locale(self, locale: str):
2222
"""
23-
Language code of which the entries needs to be included.
23+
Language code of which the entries need to be included.
2424
Only the entries published in this locale will be displayed
2525
2626
Arguments:
27-
locale {str} -- locale_code of the language of which the entries needs to be included.
27+
locale {str} -- locale_code of the language of which the entries need to be included.
2828
Only the entries published in this locale will be displayed
2929
3030
:return: self: so you can chain this call.

contentstack/https_connection.py

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,11 @@
77

88
import logging
99
import platform
10+
import json
1011
from json import JSONDecodeError
12+
import requests
13+
from requests.adapters import HTTPAdapter
14+
from requests.exceptions import HTTPError, Timeout
1115
import contentstack
1216

1317
log = logging.getLogger(__name__)
@@ -34,7 +38,7 @@ def user_agents():
3438
),
3539
'os': __get_os_platform,
3640
'Content-Type': 'application/json'}
37-
package = "contentstack-python/{}".format(contentstack.__version__)
41+
package = f"contentstack-python/{contentstack.__version__}"
3842
return {'User-Agent': str(header), "X-User-Agent": package}
3943

4044

@@ -52,10 +56,6 @@ def __init__(self, endpoint, headers, timeout, retry_strategy, live_preview):
5256

5357
def get(self, url):
5458

55-
import requests
56-
from requests.adapters import HTTPAdapter
57-
from requests.exceptions import HTTPError, Timeout
58-
5959
"""
6060
Here we create a response object, `response` which will store the request-response.
6161
We use requests.get method since we are sending a GET request.
@@ -71,15 +71,20 @@ def get(self, url):
7171
session.close()
7272
if response.encoding is None:
7373
response.encoding = 'utf-8'
74-
if response is not None:
74+
elif response is not None:
7575
return response.json()
7676
else:
77-
return {"error": "error details not found", "error_code": 422, "error_message": "unknown error"}
78-
except Timeout:
79-
raise TimeoutError('The request timed out')
80-
except ConnectionError:
81-
raise ConnectionError('Connection error occurred')
82-
except JSONDecodeError:
83-
raise TypeError('Invalid JSON in request')
84-
except HTTPError:
85-
raise HTTPError('Http Error Occurred')
77+
return {"error": "error details not found", "error_code": 422,
78+
"error_message": "unknown error"}
79+
except Timeout as timeout_err:
80+
raise TimeoutError(
81+
json.dumps({"httpStatus": 408,
82+
"message": f'Timeout error ${timeout_err.strerror}'})) from timeout_err
83+
except ConnectionError as connect_err:
84+
raise ConnectionError(json.dumps({"httpStatus": 503,
85+
"message": f'Service error ${connect_err.strerror}'})) from connect_err
86+
except JSONDecodeError as connection_err:
87+
raise TypeError(json.dumps({"httpStatus": 503,
88+
"message": 'Decoding JSON has failed.'})) from connection_err
89+
except HTTPError as http_err:
90+
raise HTTPError('Http error occurred') from http_err

contentstack/query.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import logging
77
from urllib import parse
88

9+
import empty as empty
910

1011
from contentstack.basequery import BaseQuery
1112
from contentstack.entryqueryable import EntryQueryable
@@ -43,15 +44,13 @@ class Query(BaseQuery, EntryQueryable):
4344

4445
def __init__(self, http_instance, content_type_uid):
4546
super().__init__()
46-
# BaseQuery.__init__(self)
4747
EntryQueryable.__init__(self)
4848
self.content_type_uid = content_type_uid
4949
self.http_instance = http_instance
5050
if self.content_type_uid is None:
5151
raise PermissionError(
5252
'You are not allowed here without content_type_uid')
53-
# self.base_url = '{}/content_types/{}/entries' \
54-
# .format(self.http_instance.endpoint, self.content_type_uid)
53+
self.base_url = f'{self.http_instance.endpoint}/content_types/{self.content_type_uid}/entries'
5554
self.base_url = self.__get_base_url()
5655

5756
def __get_base_url(self, endpoint=''):
@@ -60,8 +59,7 @@ def __get_base_url(self, endpoint=''):
6059
if None in (self.http_instance, self.content_type_uid):
6160
raise KeyError(
6261
'Provide valid http_instance, content_type_uid or entry_uid')
63-
url = '{}/content_types/{}/entries' \
64-
.format(self.http_instance.endpoint, self.content_type_uid)
62+
url = f'{self.http_instance.endpoint}/content_types/{self.content_type_uid}/entries'
6563

6664
return url
6765

@@ -313,8 +311,8 @@ def __execute_network_call(self):
313311
self.query_params["query"] = json.dumps(self.parameters)
314312
if 'environment' in self.http_instance.headers:
315313
self.query_params['environment'] = self.http_instance.headers['environment']
316-
# Check if live preview enabled
317314
self.__validate_live_preview()
318315
encoded_string = parse.urlencode(self.query_params, doseq=True)
319-
url = '{}?{}'.format(self.base_url, encoded_string)
316+
url = f'{self.base_url}?{encoded_string}'
317+
# url = '{}?{}'.format(self.base_url, encoded_string)
320318
return self.http_instance.get(url)

contentstack/stack.py

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,18 @@
33
this as a container that holds authentication related data.
44
"""
55

6-
# ************* Module stack **************
7-
# Your code has been rated at 10.00/10
8-
96
import enum
107
import logging
118
from urllib import parse
129
from urllib3.util import Retry
10+
11+
import contentstack
1312
from contentstack.asset import Asset
1413
from contentstack.assetquery import AssetQuery
1514
from contentstack.contenttype import ContentType
1615
from contentstack.https_connection import HTTPSConnection
1716
from contentstack.image_transform import ImageTransform
1817

19-
2018
__author__ = "ishaileshmishra (ishaileshmishra@gmail.com)"
2119
__license__ = "MIT"
2220
__version__ = '1.7.0'
@@ -35,14 +33,12 @@ class ContentstackRegion(enum.Enum):
3533

3634

3735
class Stack:
38-
3936
"""
4037
A stack can be defined as a pool of data or a container that holds all
4138
the content/assets related to a site. It is a collaboration space where multiple users can work
4239
together to create, edit, approve, and publish content.
4340
(API Reference)[https://www.contentstack.com/docs/developers/apis/content-delivery-api/#stack]:
4441
"""
45-
#from urllib3.util import Retry
4642

4743
def __init__(self, api_key: str, delivery_token: str, environment: str,
4844
host=DEFAULT_HOST,
@@ -58,7 +54,7 @@ def __init__(self, api_key: str, delivery_token: str, environment: str,
5854
Class that wraps the credentials of the authenticated user. Think of
5955
this as a container that holds authentication related data.
6056
61-
:param api_key: api_key of the stack
57+
param api_key: api_key of the stack
6258
:param delivery_token: delivery_token of the stack
6359
:param environment: environment of the stack
6460
:param host: (optional) host of the stack default is cdm.contentstack.io
@@ -78,14 +74,14 @@ def __init__(self, api_key: str, delivery_token: str, environment: str,
7874
'edit_tags_type': object | str,
7975
}
8076
```
81-
:param retry_strategy (optional) custom retry_strategy can be set.
82-
# Method to create retry_strategy: create object of Retry() and provide the
83-
# required parameters like below
77+
:param retry_strategy: (optional) custom retry_strategy can be set.
78+
Method to create retry_strategy: create object of Retry() and provide the
79+
required parameters like below
8480
**Example:**
8581
8682
>>> _strategy = Retry(total=5, backoff_factor=1, status_forcelist=[408, 429])
8783
>>> stack = contentstack.Stack("api_key", "delivery_token", "environment",
88-
live_preview={enable=True, authorization='your auth token'}, retry_strategy= _strategy)
84+
live_preview={enable=True, authorization='your auth token'}, retry_strategy= _strategy)
8985
```
9086
"""
9187
if live_preview is None:
@@ -120,19 +116,17 @@ def _validate_stack(self):
120116
raise PermissionError(
121117
'You are not permitted to the stack without valid Environment')
122118

123-
124119
if self.region.value == 'eu' and self.host == DEFAULT_HOST:
125120
self.host = 'eu-cdn.contentstack.com'
126121
elif self.region.value == 'azure-na' and self.host == DEFAULT_HOST:
127122
self.host = 'azure-na-cdn.contentstack.com'
128123
elif self.region.value != 'us':
129-
#self.host = '{}-{}'.format(self.region.value, DEFAULT_HOST)
130124
self.host = f'{self.region.value}-{DEFAULT_HOST}'
131125
self.endpoint = f'https://{self.host}/{self.version}'
132126

133127
self.headers = {
134128
'api_key': self.api_key,
135-
'access_token':self.delivery_token,
129+
'access_token': self.delivery_token,
136130
'environment': self.environment
137131
}
138132

@@ -156,7 +150,6 @@ def _validate_live_preview(self):
156150
if 'host' not in self.live_preview_dict:
157151
raise PermissionError("host is required")
158152
self.headers['authorization'] = self.live_preview_dict['authorization']
159-
# remove deliveryToken and environment
160153
self.host = self.live_preview_dict['host']
161154
self.endpoint = f'https://{self.host}/{self.version}'
162155
self.headers.pop('access_token')

contentstack/utility.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,4 @@ def get_complete_url(base_url: str, params: dict):
7373
if 'query' in params:
7474
params["query"] = json.dumps(params["query"])
7575
query = parse.urlencode(params)
76-
return '{}&{}'.format(base_url, query)
76+
return f'{base_url}&{query}'

tests/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,3 @@ def all_tests():
2727
test_module_entry,
2828
test_module_query
2929
])
30-

0 commit comments

Comments
 (0)