Skip to content

Commit c40502e

Browse files
doc string
1 parent 6d4db96 commit c40502e

File tree

4 files changed

+112
-53
lines changed

4 files changed

+112
-53
lines changed

contentstack/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,11 @@
1515

1616
# Set a default logger to prevent "No handler found" warnings
1717
import logging
18+
1819
try:
1920
from logging import NullHandler
21+
# logging.basicConfig(filename='cs.log', format='%(asctime)s - %(message)s', level=logging.DEBUG)
22+
# logging.getLogger("__init__.py")
2023
except ImportError:
2124
class NullHandler(logging.Handler):
2225
def emit(self, record):

contentstack/config.py

Lines changed: 52 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -21,67 +21,71 @@
2121
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2222
* SOFTWARE.
2323
24-
"""
24+
"""
2525
import logging
2626

2727

28-
logging.basicConfig(filename='contentstack.log', format='%(asctime)s - %(message)s', level=logging.INFO)
28+
logging.basicConfig(filename='cs.log', format='%(asctime)s - %(message)s', level=logging.INFO)
2929
logging.getLogger("Config")
3030

3131

32-
class Config:
32+
class Config(object):
33+
"""
34+
All API paths are relative to this base URL, for example, /users actually means <scheme>://<host>/<basePath>/users.
35+
36+
"""
3337

3438
def __init__(self):
35-
self.defaultConfig = dict(protocol="https:/",
36-
host="cdn.contentstack.io",
37-
port=443,
38-
version="v3",
39-
path={
40-
"stacks": "stacks",
41-
"sync": "stacks/sync",
42-
"content_types": "content_types",
43-
"entries": "content_types",
44-
"assets": "assets",
45-
"environments": "environments"
46-
})
47-
48-
def host(self, host_url=None):
49-
if host_url is not None and isinstance(host_url, str):
50-
self.defaultConfig['host'] = host_url
51-
return self.defaultConfig['host']
39+
40+
# It initialises the Config with the default endpoint
41+
self.default = dict(protocol="https", host="cdn.contentstack.io", port=443, version="v3")
42+
43+
def host(self, host):
44+
45+
"""
46+
The base URL for Content Delivery API is cdn.contentstack.io.
47+
host is the domain name or IP address (
48+
IPv4) of the host that serves the API. It may include the port number if different from the scheme's default
49+
port (443 for HTTPS).
50+
51+
Note: contentstack supports HTTPS only
52+
:param host: host is the domain name
53+
:type host: str
54+
:return: self
55+
:rtype: Config
56+
57+
Example:
58+
59+
>>> config = Config().host('api.contentstack.io')
60+
61+
"""
62+
63+
if host is not None and isinstance(host, str):
64+
self.default['host'] = host
65+
return self
5266

5367
def version(self, version=None):
54-
if version is not None and isinstance(version, str):
55-
self.defaultConfig['version'] = version
56-
return self.defaultConfig['version']
57-
else:
58-
return self.defaultConfig['version']
59-
60-
def path(self, path):
61-
url_section = self.defaultConfig['path']
62-
if path in url_section:
63-
return url_section[path]
64-
else:
65-
logging.error("{0} is invalid endpoint path".format(path))
66-
raise Exception('Invalid endpoint!!, {0} is invalid endpoint path, Path can be found among {1}'
67-
.format(path, url_section.keys()))
6868

69-
@property
70-
def default_endpoint(self):
71-
endpoint_url = "{0}/{1}/{2}".format(self.defaultConfig["protocol"], self.host(), self.version())
72-
return endpoint_url
69+
"""
70+
Note: Only version 3 is supported on the CDN. If you're still using version 2 (which we recommend you should
71+
not), switch to the CDN version for even faster loading.
72+
:param version: The API version can be found in the URL that is basePath
73+
:type version: str
74+
:return: self
75+
:rtype: Config
7376
74-
def endpoint(self, path):
75-
url = self.path(path)
76-
if url is not None and isinstance(url, str):
77-
url = "{0}/{1}/{2}/{3}".format(self.defaultConfig["protocol"], self.host(), self.version(), url)
78-
logging.info('endpoint is :: {0} '.format(url))
77+
Example: The API version (in our case, 'v3') can be found in the URL, e.g.
7978
80-
return url
79+
>>> config = Config()
80+
>>> config.version = 'v3'
8181
82+
"""
83+
if version is not None and isinstance(version, str):
84+
self.default['version'] = version
8285

83-
# config = Config()
84-
# config.host("stag-cdn.contentstack.io")
85-
# result_url = config.endpoint('assets')
86-
# print(result_url)
86+
return self
8787

88+
@property
89+
def endpoint(self):
90+
url = "{0}://{1}/{2}".format(self.default["protocol"], self.default["host"], self.default["version"])
91+
return url

contentstack/errors.py

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,54 +24,91 @@
2424

2525

2626
class Error:
27+
2728
"""
2829
contentstack.error
2930
~~~~~~~~~~~~~~~~~~
3031
This module implements the Error class.
3132
API Reference: https://www.contentstack.com/docs/apis/content-delivery-api/#error
33+
3234
"""
3335

3436
def __init__(self):
37+
38+
"""
39+
40+
"""
3541
self.__error_dict = {}
3642
self.__error_code = str
3743
self.__msg = str
3844
self.__cause_err = str
3945

4046
def config(self, result: dict):
4147

48+
"""
49+
50+
:param result:
51+
:type result:
52+
:return:
53+
:rtype:
54+
"""
4255
if result is not None and len(result) > 0:
4356
self.__error_dict = result
4457
self.__error_code = self.__error_dict['error_code']
4558
self.__msg = self.__error_dict['error_message']
4659
self.__cause_err = self.__error_dict['errors']
47-
4860
return self
4961

5062
@property
5163
def error_code(self):
64+
5265
"""
66+
It returns error code from the stack response
5367
:return: error_code as int
68+
:rtype: int
69+
70+
Example. code = error.error_code
71+
5472
"""
5573
return self.__error_code
5674

5775
@property
5876
def error_message(self):
77+
5978
"""
79+
Returns error_message from the stack response
6080
:return: error_message
81+
:rtype: str
82+
83+
Example. error.error_message
84+
6185
"""
86+
6287
return self.__msg
6388

6489
@property
6590
def error(self):
91+
6692
"""
93+
This returns error code and error_message in dict formats
6794
:return: error dict
95+
:rtype: dict
96+
97+
Example. error = error.error
6898
"""
99+
69100
return self.__cause_err
70101

71102
@property
72103
def error_info(self) -> dict:
104+
73105
"""
74-
:return: dict, error information
106+
error information
107+
:return: error information
108+
:rtype: dict
109+
110+
Example. error.error_info
111+
75112
"""
76113
return self.__error_dict
77114

contentstack/http_connection.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
2+
from json import JSONDecodeError
3+
import logging
4+
5+
16
class HTTPConnection:
27

38
def __init__(self, url: str, query: dict, headers: dict):
@@ -32,10 +37,12 @@ def get_result(self, url: str, query: dict, headers: dict):
3237
# requesting for url, payload and headers
3338
response: Response = requests.get(self.url, params=payload, headers=self.headers)
3439
# if response.status_code = 200
40+
# logging.info('Request url :: -> ', response.url)
3541
if response.ok:
3642

3743
# Decode byte response to json
3844
result = response.json()
45+
logging.info('url={}\nresponse={}'.format(response.url, result))
3946
# If result contains stack, return json response
4047
if 'stack' in result:
4148
return result['stack']
@@ -70,11 +77,12 @@ def get_result(self, url: str, query: dict, headers: dict):
7077
err = response.json()
7178
if err is not None:
7279
return Error().config(err)
73-
# raise ContentstackError('Server Error Code {} Message: {}'.format(error_code, error_message))
7480

7581
except requests.RequestException as err:
76-
# Error().config(err)
77-
raise ConnectionError(err)
82+
if isinstance(err, ConnectionError):
83+
raise ConnectionError(err)
84+
except JSONDecodeError:
85+
raise ValueError("Inappropriate response")
7886

7987
@staticmethod
8088
def __parse_entries(result):
@@ -134,3 +142,10 @@ def __user_agents() -> dict:
134142

135143
local_headers = {'X-User-Agent': str(header), "Content-Type": 'application/json'}
136144
return local_headers
145+
146+
# def is_json(self, myjson):
147+
# try:
148+
# json.loads(myjson.json())
149+
# return True
150+
# except JSONDecodeError:
151+
# return False

0 commit comments

Comments
 (0)