Skip to content

Commit 7b57e4d

Browse files
stack refactored
1 parent 6d76577 commit 7b57e4d

File tree

2 files changed

+73
-79
lines changed

2 files changed

+73
-79
lines changed

contentstack/errors.py

Lines changed: 55 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -23,39 +23,73 @@
2323
"""
2424

2525

26-
class Error(Exception):
27-
26+
class Error:
2827
"""
2928
contentstack.error
3029
~~~~~~~~~~~~~~~~~~
3130
This module implements the Error class.
3231
API Reference: https://www.contentstack.com/docs/apis/content-delivery-api/#error
33-
3432
"""
3533

3634
def __init__(self):
37-
self.error_code = str
38-
self.msg = str
39-
self.cause_err = str
35+
self.__error_dict = {}
36+
self.__error_code = str
37+
self.__msg = str
38+
self.__cause_err = str
39+
40+
def config(self, result: dict):
41+
if result is not None and len(result) > 0:
42+
self.__error_dict = result
43+
self.__error_code = self.__error_dict['error_code']
44+
self.__msg = self.__error_dict['error_message']
45+
self.__cause_err = self.__error_dict['errors']
46+
47+
@property
48+
def error_code(self):
49+
"""
50+
:return: error_code as int
51+
"""
52+
return self.__error_code
53+
54+
@property
55+
def error_message(self):
56+
"""
57+
:return: error_message
58+
"""
59+
return self.__msg
60+
61+
@property
62+
def error(self):
63+
"""
64+
:return: error dict
65+
"""
66+
return self.__cause_err
67+
68+
@property
69+
def error_info(self) -> dict:
70+
71+
"""
72+
:return: dict, error information
73+
"""
74+
return self.__error_dict
4075

4176
errors_str = {
4277

43-
'error_invalid_json': "Please provide valid JSON.",
44-
'error_message_stack_api_key_is_null': "Stack api key can not be null.",
45-
'error_form_name': "Please set contentType name.",
46-
'error_stack_access_token_is_null': "Access token can not be null.",
47-
'error_stack_environment_is_null': "Environment can not be null.",
48-
'Error_Connection_Error': "Connection error",
49-
'Error_Auth_Failure_Error': "Authentication Not present.",
50-
'Error_Parse_Error': "Parsing Error.",
51-
'Error_Server_Error': "Server interaction went wrong, Please try again.",
52-
'Error_Default': "Oops! Something went wrong. Please try again.",
53-
'Error_No_Network': "Network not available.",
54-
'Error_Called_Default_Method': "You must called Contentstack.stack() first",
55-
'Error_Query_Filter_Exception': "Please provide valid params."
78+
'invalid_json': "Please provide valid JSON.",
79+
'api_key_is_none': "Stack api key can not be None.",
80+
'empty_content_type': "Please set contentType name.",
81+
'access_token_error': "Access token can not be None.",
82+
'environment_error': "Environment can not be None.",
83+
'connection_error': "Connection error",
84+
'auth_failure': "Authentication Not present.",
85+
'parse_error': "Parsing Error.",
86+
'server_error': "Server interaction went wrong, Please try again.",
87+
'error_default': "Oops! Something went wrong. Please try again.",
88+
'no_network': "Network not available.",
89+
'query_error': "Please provide valid params."
5690
}
5791

58-
error_code = {
92+
__error_code = {
5993

6094
400: "The request was incorrect or corrupted.",
6195
401: "The login credentials are invalid.",
@@ -69,70 +103,19 @@ def __init__(self):
69103
504: "A server did not receive a timely response from another server that it was accessing while attempting to load the web page or fill another request by the browser."
70104
}
71105

72-
exceptions = {
73-
74-
AssertionError: "Raised when the assert statement fails.",
75-
AttributeError: "Raised on the attribute assignment or reference fails.",
76-
EOFError: "Raised when the input() function hits the end-of-file condition.",
77-
FloatingPointError: "Raised when a floating point operation fails.",
78-
GeneratorExit: "Raised when a generator's close() method is called.",
79-
ImportError: "Raised when the imported module is not found.",
80-
IndexError: "Raised when the index of a sequence is out of range.",
81-
KeyError: "Raised when a key is not found in a dictionary.",
82-
KeyboardInterrupt: "Raised when the user hits the interrupt key (Ctrl+c or delete).",
83-
MemoryError: "Raised when an operation runs out of memory.",
84-
NameError: "Raised when a variable is not found in the local or global scope.",
85-
NotImplementedError: "Raised by abstract methods.",
86-
OSError: "Raised when a system operation causes a system-related error.",
87-
OverflowError: "Raised when the result of an arithmetic operation is too large to be represented.",
88-
ReferenceError: "Raised when a weak reference proxy is used to access a garbage collected referent.",
89-
RuntimeError: "Raised when an error does not fall under any other category.",
90-
StopIteration: "Raised by the next() function to indicate that there is no further item to be returned by the iterator.",
91-
SyntaxError: "Raised by the parser when a syntax error is encountered.",
92-
IndentationError: "Raised when there is an incorrect indentation.",
93-
TabError: "Raised when the indentation consists of inconsistent tabs and spaces.",
94-
SystemError: "Raised when the interpreter detects internal error.",
95-
SystemExit: "Raised by the sys.exit() function.",
96-
TypeError: "Raised when a function or operation is applied to an object of an incorrect type.",
97-
UnboundLocalError: "Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.",
98-
UnicodeError: "Raised when a Unicode-related encoding or decoding error occurs.",
99-
UnicodeEncodeError: "Raised when a Unicode-related error occurs during encoding.",
100-
UnicodeDecodeError: "Raised when a Unicode-related error occurs during decoding.",
101-
UnicodeTranslateError: "Raised when a Unicode-related error occurs during translation.",
102-
ValueError: "Raised when a function gets an argument of correct type but improper value.",
103-
ZeroDivisionError: "Raised when the second operand of a division or module operation is zero."
104-
105-
}
106-
107-
def error(self, response: dict) -> tuple:
108-
if response is not None and isinstance(response, dict):
109-
self.error_code = response['error_code']
110-
self.msg = response['error_message']
111-
self.cause_err = response['errors']
112-
113-
return self.error_code, self.msg, self.cause_err
114-
115106
@staticmethod
116107
def logging_config(level):
108+
117109
print('level ' + level)
118110

119111

120112
class ConfigError(Exception):
121-
"""Configuration Error Class"""
122113
pass
123114

124115

125116
class StackException(Exception):
126-
"""StackException Class"""
127117
pass
128118

129119

130120
class NotSupportedException(Exception):
131-
""" exception is thrown when something is not supported by the API."""
132121
pass
133-
134-
135-
class retry_request(object):
136-
"""
137-
Decorator to retry function calls in case they raise rate limit exceptions
138-
"""

contentstack/http_connection.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
12
class HTTPConnection:
23

34
def __init__(self, url: str, query: dict, headers: dict):
@@ -7,14 +8,15 @@ def __init__(self, url: str, query: dict, headers: dict):
78
self.query = query
89
self.headers = headers
910
else:
10-
raise TypeError('Invalid Arguments')
11+
raise TypeError('Kindly provide valid Arguments')
1112

1213
def get_result(self, url: str, query: dict, headers: dict) -> tuple:
1314

1415
import requests
1516
from urllib import parse
1617
from requests import Response
1718
from contentstack.stack import SyncResult
19+
from contentstack import Error
1820

1921
if url is not None and len(url) > 0:
2022
self.url = url
@@ -29,7 +31,6 @@ def get_result(self, url: str, query: dict, headers: dict) -> tuple:
2931
payload = parse.urlencode(query=self.query, encoding='UTF-8')
3032

3133
try:
32-
3334
# requesting for url, payload and headers
3435
response: Response = requests.get(self.url, params=payload, headers=self.headers)
3536
# if response.status_code = 200
@@ -40,37 +41,44 @@ def get_result(self, url: str, query: dict, headers: dict) -> tuple:
4041
# If result contains stack, return json response
4142
if 'stack' in result:
4243
return result['stack']
44+
4345
# If result contains entry, return Entry
4446
if 'entry' in result:
4547
dict_entry = result['entry']
4648
return self.__parse_entries(dict_entry)
49+
4750
# If result contains entries, return list[Entry]
4851
if 'entries' in result:
4952
entry_list = result['entries']
5053
return self.__parse_entries(entry_list)
54+
5155
# If result contains asset, return Asset
5256
if 'asset' in result:
5357
dict_asset = result['asset']
5458
return self.__parse_assets(dict_asset)
59+
5560
# If result contains assets, return list[Asset]
5661
if 'assets' in result:
5762
asset_list = result['assets']
5863
return self.__parse_assets(asset_list)
59-
# If result contains content_type, return content_type json
64+
65+
# If result contains content_type,return content_type json
6066
if 'content_type' in result:
6167
return result['content_type']
62-
# If result contains content_types, return content_types json
68+
69+
# If result contains content_types,return content_types json
6370
if 'content_types' in result:
6471
return result['content_types']
65-
# If result contains items, return SyncResult json
72+
6673
# If result contains items, return SyncResult json
6774
if 'items' in result:
6875
sync_result = SyncResult().configure(result)
6976
return sync_result
70-
7177
else:
7278
# Decode byte response to json
73-
return response.json()
79+
err = response.json()
80+
if err is not None:
81+
return Error().config(err)
7482

7583
except requests.RequestException as err:
7684
raise ConnectionError(err)
@@ -88,6 +96,7 @@ def __parse_entries(result):
8896
for entry_obj in result:
8997
each_entry = Entry().configure(entry_obj)
9098
entries.append(each_entry)
99+
91100
return entries
92101

93102
@staticmethod
@@ -103,6 +112,7 @@ def __parse_assets(result):
103112
for asset_obj in result:
104113
itr_asset = asset.configure(asset_obj)
105114
assets.append(itr_asset)
115+
106116
return assets
107117

108118
@staticmethod
@@ -131,5 +141,6 @@ def __user_agents() -> dict:
131141
'name': os_name,
132142
'version': platform.release()
133143
}
144+
134145
local_headers = {'X-User-Agent': str(header), "Content-Type": 'application/json'}
135146
return local_headers

0 commit comments

Comments
 (0)