Skip to content

Commit 25b918d

Browse files
query added
1 parent 0b4bc95 commit 25b918d

File tree

3 files changed

+103
-42
lines changed

3 files changed

+103
-42
lines changed

contentstack/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from .asset_library import AssetLibrary
1313
from .config import Config
1414
from .content_type import ContentType
15-
from .errors import HTTPError, ConfigError
15+
from .errors import Error, ConfigError
1616
from .group import Group
1717
from .http_request import HTTPRequestConnection
1818

contentstack/asset_library.py

Lines changed: 86 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -23,53 +23,52 @@
2323
*
2424
"""
2525

26-
from contentstack import http_request
27-
28-
"""
29-
contentstack.asset_library
30-
~~~~~~~~~~~~~~~~~~
31-
This module implements the AssetLibrary class.
32-
API Reference: https://www.contentstack.com/docs/apis/content-delivery-api/#assets
33-
34-
"""
35-
3626

3727
class AssetLibrary:
28+
"""
29+
contentstack.asset_library
30+
~~~~~~~~~~~~~~~~~~
31+
This module implements the AssetLibrary class.
32+
API Reference: https://www.contentstack.com/docs/apis/content-delivery-api/#assets
33+
34+
"""
3835

3936
def __init__(self):
4037
self.count = 0
41-
self.__local_header: dict = {}
42-
self.__post_params: dict = {}
38+
self.__local_headers = {}
39+
self.__query_params = {}
4340

4441
def set_header(self, key: str, value):
4542
if key is not None and value is not None:
46-
self.__local_header[key] = value
43+
self.__local_headers[key] = value
4744
return self
4845

49-
def set_headers(self, **headers):
50-
if headers is not None:
51-
self.__local_header = headers
52-
for key, value in self.__local_header.items():
53-
self.__local_header[key] = value
46+
def headers(self, headers: dict):
47+
if headers is not None and len(headers) > 0 and isinstance(headers, dict):
48+
self.__local_headers = headers
49+
if 'environment' in self.__local_headers:
50+
env_value = self.__local_headers['environment']
51+
self.__query_params["environment"] = env_value
5452
return self
5553

5654
def remove_header(self, key):
5755
if key is not None:
58-
if key in self.__local_header:
59-
self.__local_header.pop(key)
56+
if key in self.__local_headers:
57+
self.__local_headers.pop(key)
6058
return self
6159

6260
def include_count(self):
63-
self.__post_params['include_count'] = 'true'
61+
self.__query_params['include_count'] = 'true'
6462
return self
6563

6664
def include_relative_url(self):
67-
self.__post_params['relative_urls'] = 'true'
65+
self.__query_params['relative_urls'] = 'true'
6866
return self
6967

7068
def get_count(self) -> int:
7169
return self.count
7270

71+
# Color = enumerate(RED="ASCENDING", GREEN='DESCENDING')
7372
# [PENDING], Need to add
7473
# order_by = Enum('ORDER_BY', 'ASCENDING DESCENDING')
7574
# def sort(self, key: str, order_by):
@@ -79,18 +78,68 @@ def get_count(self) -> int:
7978
# self.__post_params['desc'] = key
8079
# return self.__post_params
8180

82-
def fetch(self) -> tuple:
83-
print('__params ::', self.__post_params)
84-
print('__headers ::', self.__local_header)
85-
asset_request = http_request.HTTPRequestConnection('assets', self.__post_params, self.__local_header)
86-
(response, error) = asset_request.http_request()
87-
if error is None:
88-
print(response)
89-
self.__set_response(response['assets'])
90-
return response, error
91-
else:
92-
return response, error
93-
94-
def __set_response(self, param):
95-
96-
pass
81+
def fetch_all(self) -> tuple:
82+
83+
import requests
84+
from urllib import parse
85+
from requests import Response
86+
from contentstack import Config
87+
from contentstack import Error
88+
from contentstack import Asset
89+
90+
error = None
91+
asset_url = Config().endpoint('assets')
92+
self.__local_headers.update(self.header_agents())
93+
payload = parse.urlencode(query=self.__query_params, encoding='UTF-8')
94+
95+
try:
96+
response: Response = requests.get(asset_url, params=payload, headers=self.__local_headers)
97+
list_asset: list[Asset] = []
98+
99+
if response.ok:
100+
101+
response: dict = response.json()['assets']
102+
103+
for asset in response:
104+
asset_instance = Asset()
105+
asset_resp: Asset = asset_instance.configure(response=asset)
106+
list_asset.append(asset_resp)
107+
else:
108+
109+
error_dict = response.json()
110+
Error().error(error_dict)
111+
112+
return list_asset, error
113+
114+
except requests.exceptions.RequestException as e:
115+
raise ConnectionError(e.response)
116+
pass
117+
118+
@classmethod
119+
def header_agents(cls) -> dict:
120+
121+
import contentstack
122+
import platform
123+
124+
"""
125+
Contentstack-User-Agent header.
126+
"""
127+
header = {'sdk': dict(name=contentstack.__package__, version=contentstack.__version__)}
128+
os_name = platform.system()
129+
130+
if os_name == 'Darwin':
131+
os_name = 'macOS'
132+
133+
elif not os_name or os_name == 'Java':
134+
os_name = None
135+
136+
elif os_name and os_name not in ['macOS', 'Windows']:
137+
os_name = 'Linux'
138+
139+
header['os'] = {
140+
'name': os_name,
141+
'version': platform.release()
142+
}
143+
144+
local_headers = {'X-User-Agent': str(header), "Content-Type": 'application/json'}
145+
return local_headers

contentstack/errors.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,21 @@
2323
"""
2424

2525

26-
class HTTPError(Exception):
26+
class Error(Exception):
2727

2828
"""
2929
contentstack.error
3030
~~~~~~~~~~~~~~~~~~
3131
This module implements the Error class.
3232
API Reference: https://www.contentstack.com/docs/apis/content-delivery-api/#error
33+
3334
"""
3435

36+
def __init__(self):
37+
self.error_code = ''
38+
self.msg = ''
39+
self.cause_err = ''
40+
3541
errors_str = {
3642

3743
'error_invalid_json': "Please provide valid JSON.",
@@ -98,10 +104,16 @@ class HTTPError(Exception):
98104

99105
}
100106

101-
def get_error(self, response):
102-
print('Error')
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
103114

104-
def set_logging_config(self, level):
115+
@staticmethod
116+
def logging_config(level):
105117
print('level ' + level)
106118

107119

0 commit comments

Comments
 (0)