Skip to content

Commit 2d70d56

Browse files
live_preview 🏆
1 parent d70169b commit 2d70d56

File tree

4 files changed

+78
-94
lines changed

4 files changed

+78
-94
lines changed

contentstack/query.py

Lines changed: 15 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -321,62 +321,20 @@ def __execute_network_call(self):
321321
self.__validate_live_preview()
322322
encoded_string = parse.urlencode(self.query_params, doseq=True)
323323
url = f'{self.base_url}?{encoded_string}'
324-
# url = '{}?{}'.format(self.base_url, encoded_string)
325-
if 'content_type_uid' in self.http_instance.live_preview and 'live_preview' in url:
326-
query_response = self.http_instance.get(url)
327-
return self._map_live_preview(query_response)
324+
if self.http_instance.live_preview['content_type_uid'] == self.content_type_uid:
325+
_rq = self.http_instance.get(url)['entries']
326+
_preview = self.http_instance.live_preview['resp']
327+
return self._merge_preview(_rq, _preview)
328328
return self.http_instance.get(url)
329329

330-
def _map_live_preview(self, query_response):
331-
_preview = self.http_instance.live_preview['resp'] # Gets Live Preview Stored Data From Dict
332-
if 'entries' in query_response:
333-
query_response = query_response['entries']
334-
for index, it in enumerate(query_response): # it in query_response:
335-
if isinstance(it, dict):
336-
if it['uid'] == _preview['uid']:
337-
# return self.merge_it(self.resp, _preview)
338-
merged = {**query_response[index], **_preview}
339-
return query_response
340-
# self._map_live_preview(query_response)
341-
# elif isinstance(query_response, list):
342-
# for obj in query_response:
343-
# self.iter_dict(obj,_preview['uid'])
344-
# pass
345-
else:
346-
return None
347-
348-
# def iter_dict(self, item, uid):
349-
# if isinstance(item, dict):
350-
# if item['uid'] == uid:
351-
# # return self.merge_it(self.resp, preview_response)
352-
# merged = {**query_response[index], **preview_response}
353-
# return merged
354-
# self._map_live_preview(query_response)
355-
356-
def merge_it(self, resp, lp_resp):
357-
resp.update(lp_resp)
358-
# merged
359-
merged = {**resp, **lp_resp}
360-
print(f"merged: {merged}")
361-
return resp
362-
363-
def deep_merge(self, resp, lp_resp):
364-
query_set = set(resp)
365-
live_set = set(lp_resp)
366-
store_keys = []
367-
for key in live_set.intersection(query_set): # Iterates for common keys between query & livePreview
368-
store_keys.append(key)
369-
if isinstance(resp[key], dict):
370-
# match keys and update value
371-
self.merge_it(resp[key], lp_resp[key])
372-
elif isinstance(resp[key], list):
373-
# match keys and update value
374-
for i in lp_resp[key]:
375-
if isinstance(resp[i], dict):
376-
self.merge_it(resp[key], lp_resp[key])
377-
resp.update({key: f"New Fake:{lp_resp[key]}"})
378-
resp.update({key: f"New Fake:{lp_resp[key]}"})
379-
380-
# name, myNames[name]
381-
print(f"new query resp: {resp}")
382-
print(f"store_keys {store_keys}")
330+
def _merge_preview(self, qresp, _preview):
331+
if isinstance(qresp, dict):
332+
if 'uid' in qresp and qresp['uid'] == _preview['uid']:
333+
merged = {**qresp, **_preview} # TODO: Check merging
334+
else:
335+
for key in dict.keys():
336+
qresp[key] = self._merge(qresp[key])
337+
elif isinstance(qresp, list):
338+
for index, it in enumerate(qresp):
339+
qresp[index] = self._merge_preview(it, _preview)
340+
return qresp

contentstack/stack.py

Lines changed: 35 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def __init__(self, api_key: str, delivery_token: str, environment: str,
5050
branch=None,
5151
):
5252
"""
53-
Class that wraps the credentials of the authenticated user. Think of
53+
# Class that wraps the credentials of the authenticated user. Think of
5454
this as a container that holds authentication related data.
5555
5656
param api_key: api_key of the stack
@@ -65,13 +65,13 @@ def __init__(self, api_key: str, delivery_token: str, environment: str,
6565
takes input as dictionary object. containing one/multiple key value pair like below.
6666
6767
```python
68-
live_preview = {
69-
'enable': True,
68+
live_preview = {
69+
'enable': True,
7070
'authorization': 'your_management_token',
7171
'host': 'api.contentstack.com',
7272
'include_edit_tags': True,
7373
'edit_tags_type': object | str,
74-
}
74+
}
7575
```
7676
:param retry_strategy: (optional) custom retry_strategy can be set.
7777
Method to create retry_strategy: create object of Retry() and provide the
@@ -101,20 +101,23 @@ def __init__(self, api_key: str, delivery_token: str, environment: str,
101101
self.timeout = timeout
102102
self.branch = branch
103103
self.retry_strategy = retry_strategy
104-
self.live_preview_dict = live_preview
104+
self.live_preview = live_preview
105105

106106
self._validate_stack()
107107

108108
def _validate_stack(self):
109109
if self.api_key is None or self.api_key == '':
110110
raise PermissionError(
111-
'You are not permitted to the stack without valid APIKey')
111+
'You are not permitted to the stack without valid APIKey'
112+
)
112113
if self.delivery_token is None or self.delivery_token == "":
113114
raise PermissionError(
114-
'You are not permitted to the stack without valid Delivery Token')
115+
'You are not permitted to the stack without valid Delivery Token'
116+
)
115117
if self.environment is None or self.environment == "":
116118
raise PermissionError(
117-
'You are not permitted to the stack without valid Environment')
119+
'You are not permitted to the stack without valid Environment'
120+
)
118121

119122
if self.region.value == 'eu' and self.host == DEFAULT_HOST:
120123
self.host = 'eu-cdn.contentstack.com'
@@ -133,24 +136,14 @@ def _validate_stack(self):
133136
if self.branch is not None:
134137
self.headers['branch'] = self.branch
135138

136-
if self.live_preview_dict is not None:
137-
self._validate_live_preview()
138139
self.http_instance = HTTPSConnection(
139140
endpoint=self.endpoint,
140-
headers=self.headers, timeout=self.timeout,
141+
headers=self.headers,
142+
timeout=self.timeout,
141143
retry_strategy=self.retry_strategy,
142-
live_preview=self.live_preview_dict
144+
live_preview=self.live_preview
143145
)
144146

145-
def _validate_live_preview(self):
146-
if isinstance(self.live_preview_dict, dict):
147-
if 'enable' in self.live_preview_dict and self.live_preview_dict['enable']:
148-
self.headers['authorization'] = self.live_preview_dict['authorization']
149-
self.host = self.live_preview_dict['host']
150-
self.endpoint = f'https://{self.host}/{self.version}'
151-
self.headers.pop('access_token')
152-
self.headers.pop('environment')
153-
154147
@property
155148
def get_api_key(self):
156149
"""
@@ -191,7 +184,7 @@ def get_live_preview(self):
191184
"""
192185
:return: live preview dictionary
193186
"""
194-
return self.live_preview_dict
187+
return self.live_preview
195188

196189
def content_type(self, content_type_uid=None):
197190
"""
@@ -360,14 +353,28 @@ def live_preview_query(self, **kwargs):
360353
hash='hashcode'
361354
)
362355
"""
363-
self.live_preview_dict.update(kwargs)
356+
self.live_preview.update(kwargs)
364357
self._execute_management_api()
365358
return self
366359

367360
def _execute_management_api(self):
368-
_ct_uid = self.live_preview_dict.get("content_type_uid")
369-
_entry_uid = self.live_preview_dict.get("entry_uid")
370-
_url = f'{self.http_instance.endpoint}/content_types/{_ct_uid}/entries/{_entry_uid}'
371-
_resp = self.http_instance.get(_url)
372-
self.live_preview_dict['resp'] = _resp['entry']
361+
_headers, _endpoint = self._enable_live_preview()
362+
_ct_uid = self.live_preview.get("content_type_uid")
363+
_entry_uid = self.live_preview.get("entry_uid")
364+
_url = f'{_endpoint}/content_types/{_ct_uid}/entries/{_entry_uid}'
365+
import requests
366+
r = requests.get(url=_url, verify=True, headers=_headers)
367+
# _resp = self.http_instance.get(_url, headers=_headers)
368+
self.live_preview['resp'] = r.json()['entry']
373369
return self
370+
371+
def _enable_live_preview(self):
372+
if isinstance(self.live_preview, dict) and not None:
373+
_endpoint = None
374+
_local_headers = {}
375+
if 'enable' in self.live_preview and self.live_preview['enable']:
376+
_local_headers['authorization'] = self.live_preview['authorization']
377+
_host = self.live_preview['host']
378+
_endpoint = f'https://{_host}/{self.version}'
379+
_local_headers['api_key'] = self.headers['api_key']
380+
return _local_headers, _endpoint

tests/test_entry.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,5 +156,6 @@ def test_21_entry_include_embedded_items(self):
156156
self.assertEqual({'environment': 'development',
157157
'include_embedded_items[]': 'BASE'}, entry.entry_param)
158158

159-
# if __name__ == '__main__':
160-
# unittest.main()
159+
160+
if __name__ == '__main__':
161+
unittest.main()
Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,26 +41,26 @@ def test_021_live_preview_enabled_(self):
4141
ENVIRONMENT,
4242
live_preview=_preview)
4343
self.assertEqual(_preview['authorization'],
44-
self.stack.live_preview_dict['authorization'])
44+
self.stack.live_preview['authorization'])
4545

4646
def test_03_set_host(self):
4747
self.stack = contentstack.Stack(
4848
API_KEY,
4949
DELIVERY_TOKEN,
5050
ENVIRONMENT,
5151
live_preview=_preview)
52-
self.assertEqual(3, len(self.stack.live_preview_dict))
53-
self.assertEqual(True, self.stack.live_preview_dict['enable'])
52+
self.assertEqual(3, len(self.stack.live_preview))
53+
self.assertEqual(True, self.stack.live_preview['enable'])
5454

5555
def test_031_set_host_value(self):
5656
self.stack = contentstack.Stack(
5757
API_KEY,
5858
DELIVERY_TOKEN,
5959
ENVIRONMENT,
6060
live_preview=_preview)
61-
self.assertEqual(3, len(self.stack.live_preview_dict))
61+
self.assertEqual(3, len(self.stack.live_preview))
6262
self.assertEqual(_preview['host'],
63-
self.stack.live_preview_dict['host'])
63+
self.stack.live_preview['host'])
6464

6565
def test_06_live_preview_query(self):
6666
_live_preview = {
@@ -74,7 +74,7 @@ def test_06_live_preview_query(self):
7474
ENVIRONMENT,
7575
live_preview=_preview
7676
)
77-
self.assertEqual(5, len(self.stack.live_preview_dict))
77+
self.assertEqual(5, len(self.stack.live_preview))
7878

7979
def test_07_live_preview_query_hash_included(self):
8080
self.stack = contentstack.Stack(
@@ -86,7 +86,7 @@ def test_07_live_preview_query_hash_included(self):
8686
self.stack.live_preview_query(
8787
hash='live_preview',
8888
content_type_uid='fake@content_type')
89-
self.assertEqual(7, len(self.stack.live_preview_dict))
89+
self.assertEqual(7, len(self.stack.live_preview))
9090

9191
def test_08_live_preview_query_hash_excluded(self):
9292
self.stack = contentstack.Stack(
@@ -125,6 +125,24 @@ def test_branching(self):
125125
stack.content_type('product')
126126
self.assertEqual('dev_branch', stack.get_branch)
127127

128+
def test_live_preview(self):
129+
__preview = {
130+
'enable': True,
131+
'authorization': 'management_token',
132+
'host': 'api.contentstack.io'
133+
}
134+
stack = contentstack.Stack(
135+
'api_key',
136+
'delivery_token',
137+
'development',
138+
live_preview=__preview).live_preview_query(
139+
entry_uid='entry_uid',
140+
content_type_uid='bugfixes',
141+
hash='#Just_fake_it'
142+
)
143+
result = stack.content_type(content_type_uid='bugfixes').query().find()
144+
print(result)
145+
128146

129147
if __name__ == '__main__':
130148
unittest.main()

0 commit comments

Comments
 (0)