Skip to content

Commit 08fed21

Browse files
- removed print() from tests directory
- changelog.rst latest version date updated
1 parent 1cb1872 commit 08fed21

File tree

11 files changed

+165
-126
lines changed

11 files changed

+165
-126
lines changed

README.md

Lines changed: 53 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,17 @@
77

88
## Python SDK for Contentstack
99

10-
Contentstack is a headless CMS with an API-first approach. It is a CMS that developers can use to build powerful cross-platform applications in their favorite languages. Build your application frontend, and Contentstack will take care of the rest. [Read More](https://www.contentstack.com/).
10+
Contentstack is a headless CMS with an API-first approach. It is a CMS that developers can use to build powerful
11+
cross-platform applications in their favorite languages. Build your application frontend, and Contentstack will take
12+
care of the rest. [Read More](https://www.contentstack.com/).
1113

12-
Contentstack provides Python SDK to build application on top of Python. Given below is the detailed guide and helpful resources to get started with our Python SDK.
14+
Contentstack provides Python SDK to build application on top of Python. Given below is the detailed guide and helpful
15+
resources to get started with our Python SDK.
1316

1417
### Prerequisite
1518

16-
You will need python 3 installed on your machine. You can install it from [here](https://www.python.org/ftp/python/3.7.4/python-3.7.4-macosx10.9.pkg).
19+
You will need python 3 installed on your machine. You can install it
20+
from [here](https://www.python.org/ftp/python/3.7.4/python-3.7.4-macosx10.9.pkg).
1721

1822
### Setup and Installation
1923

@@ -27,48 +31,61 @@ pip install contentstack
2731

2832
Install latest [contentstack](https://pypi.org/project/Contentstack) package from the [PyPI](https://pypi.org)
2933

30-
This is the preferred method to install contentstack, as it will always install the most recent stable release. If you don't have [pip](https://pip.pypa.io/) installed, this [Python installation guide](http://docs.python-guide.org/en/latest/starting/installation/) can guide you through the process
34+
This is the preferred method to install contentstack, as it will always install the most recent stable release. If you
35+
don't have [pip](https://pip.pypa.io/) installed,
36+
this [Python installation guide](http://docs.python-guide.org/en/latest/starting/installation/) can guide you through
37+
the process
3138

3239
### Key Concepts for using Contentstack
3340

3441
#### Stack
3542

36-
A stack is like a container that holds the content of your app. Learn more about [Stacks](https://www.contentstack.com/docs/developers/set-up-stack).
43+
A stack is like a container that holds the content of your app. Learn more
44+
about [Stacks](https://www.contentstack.com/docs/developers/set-up-stack).
3745

3846
#### Content Type
3947

40-
Content type lets you define the structure or blueprint of a page or a section of your digital property. It is a form-like page that gives Content Managers an interface to input and upload content. [Read more](https://www.contentstack.com/docs/developers/create-content-types).
48+
Content type lets you define the structure or blueprint of a page or a section of your digital property. It is a
49+
form-like page that gives Content Managers an interface to input and upload
50+
content. [Read more](https://www.contentstack.com/docs/developers/create-content-types).
4151

4252
#### Entry
4353

44-
An entry is the actual piece of content created using one of the defined content types. Learn more about [Entries](https://www.contentstack.com/docs/content-managers/work-with-entries).
54+
An entry is the actual piece of content created using one of the defined content types. Learn more
55+
about [Entries](https://www.contentstack.com/docs/content-managers/work-with-entries).
4556

4657
#### Asset
4758

48-
Assets refer to all the media files (images, videos, PDFs, audio files, and so on) uploaded to Contentstack. These files can be used in multiple entries. Read more about [Assets](https://www.contentstack.com/docs/content-managers/work-with-assets).
59+
Assets refer to all the media files (images, videos, PDFs, audio files, and so on) uploaded to Contentstack. These files
60+
can be used in multiple entries. Read more
61+
about [Assets](https://www.contentstack.com/docs/content-managers/work-with-assets).
4962

5063
#### Environment
5164

52-
A publishing environment corresponds to one or more deployment servers or a content delivery destination where the entries need to be published. Learn how to work with [Environments](https://www.contentstack.com/docs/developers/set-up-environments).
65+
A publishing environment corresponds to one or more deployment servers or a content delivery destination where the
66+
entries need to be published. Learn how to work
67+
with [Environments](https://www.contentstack.com/docs/developers/set-up-environments).
5368

5469
### Contentstack Python SDK: 5-minute Quickstart
5570

5671
#### Initializing your SDK
5772

58-
To initialize the SDK, specify application API key, access token, and environment name of the stack as shown in the snippet given below, You can provide optional parameters for config:
73+
To initialize the SDK, specify application API key, access token, and environment name of the stack as shown in the
74+
snippet given below, You can provide optional parameters for config:
5975

6076
```python
61-
stack = contentstack.Stack('api_key','delivery_token','environment')
77+
stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
6278
```
6379

64-
To get the API credentials mentioned above, log in to your Contentstack account and then in your top panel navigation, go to Settings > Stack to view the API Key and Access Token.
80+
To get the API credentials mentioned above, log in to your Contentstack account and then in your top panel navigation,
81+
go to Settings > Stack to view the API Key and Access Token.
6582

6683
#### Querying content from your stack
6784

6885
To retrieve a single entry from a content type use the code snippet given below:
6986

7087
```python
71-
stack = contentstack.Stack('api_key','delivery_token','environment')
88+
stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
7289
content_type = stack.content_type("content_type_uid")
7390
entry = content_type.entry("entry_uid")
7491
result = entry.fetch()
@@ -79,7 +96,7 @@ result = entry.fetch()
7996
To retrieve multiple entries of a particular content type, use the code snippet given below:
8097

8198
```python
82-
stack = contentstack.Stack('api_key','delivery_token','environment')
99+
stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
83100
query = stack.content_type("content_type_uid").query()
84101
result = query.find()
85102
```
@@ -92,9 +109,12 @@ You can query for content types, entries, assets and more using our Python API R
92109

93110
### Working with Images
94111

95-
We have introduced Image Delivery APIs that let you retrieve images and then manipulate and optimize them for your digital properties. It lets you perform a host of other actions such as crop, trim, resize, rotate, overlay, and so on.
112+
We have introduced Image Delivery APIs that let you retrieve images and then manipulate and optimize them for your
113+
digital properties. It lets you perform a host of other actions such as crop, trim, resize, rotate, overlay, and so on.
96114

97-
For example, if you want to crop an image (with width as 300 and height as 400), you simply need to append query parameters at the end of the image URL, such as, `https://images.contentstack.io/v3/assets/download?crop=300,400`. There are several more parameters that you can use for your images.
115+
For example, if you want to crop an image (with width as 300 and height as 400), you simply need to append query
116+
parameters at the end of the image URL, such as, `https://images.contentstack.io/v3/assets/download?crop=300,400`. There
117+
are several more parameters that you can use for your images.
98118

99119
[Read Image Delivery API documentation](https://www.contentstack.com/docs/platforms/python/api-reference/).
100120

@@ -108,13 +128,15 @@ image = stack.image_transform(url, {'auto': 'webp'}).get_url()
108128

109129
### Using the Sync API with Python SDK
110130

111-
The Sync API takes care of syncing your Contentstack data with your application and ensures that the data is always up-to-date by providing delta updates. Contentstack’s Python SDK supports Sync API, which you can use to build powerful applications.
131+
The Sync API takes care of syncing your Contentstack data with your application and ensures that the data is always
132+
up-to-date by providing delta updates. Contentstack’s Python SDK supports Sync API, which you can use to build powerful
133+
applications.
112134

113135
```python
114-
stack = contentstack.Stack('api_key','delivery_token','environment') #initialize sync
115-
response = stack.sync_init() #sycn using sync token
116-
response = stack.sync_token('sync_token') #sycn using pagination token
117-
response = stack.pagination('pagination_token') #sync using multiple parameters
136+
stack = contentstack.Stack('api_key', 'delivery_token', 'environment') # initialize sync
137+
response = stack.sync_init() # sycn using sync token
138+
response = stack.sync_token('sync_token') # sycn using pagination token
139+
response = stack.pagination('pagination_token') # sync using multiple parameters
118140
response = stack.sync_init(publish_type='entry_published', content_type_uid='content_type_uid')
119141
```
120142

@@ -132,10 +154,17 @@ Read through to understand how to use the Sync API with Contentstack Python SDK.
132154

133155
Copyright © 2012-2023 [Contentstack](https://www.contentstack.com/). All Rights Reserved
134156

135-
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
157+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
158+
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
159+
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
160+
persons to whom the Software is furnished to do so, subject to the following conditions:
136161

137-
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
162+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
163+
Software.
138164

139-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
165+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
166+
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
167+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
168+
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
140169

141170
- [Content Delivery API Docs](https://contentstack.com/docs/apis/content-delivery-api/)

changelog.rst

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@
55
*v1.8.0*
66
============
77

8-
**Date: 09-MAY-2023**
8+
**Date: 10-MAY-2023**
99

10-
- AZURE_EU, region support added
11-
- include_metadata support added to asset, entry and query
10+
- AZURE_EU, Region support added
11+
- Include Metadata support added to asset, entry and query
1212
- General code improvement clean up
13+
- Changes done for Live Preview
1314

1415

1516
*v1.7.0*

contentstack/contenttype.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,5 @@ def find(self, params=None):
118118
encoded_params = parse.urlencode(self.local_param)
119119
endpoint = self.http_instance.endpoint
120120
url = f'{endpoint}/content_types?{encoded_params}'
121-
# url = '{}?{}'.format(
122-
# '{}/content_types'.format(self.http_instance.endpoint), encoded_params)
123121
result = self.http_instance.get(url)
124122
return result

contentstack/entry.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,4 +194,12 @@ def fetch(self):
194194
self.entry_param.update(self.entry_queryable_param)
195195
encoded_string = parse.urlencode(self.entry_param, doseq=True)
196196
url = f'{self.base_url}?{encoded_string}'
197+
self._validate_live_preview()
197198
return self.http_instance.get(url)
199+
200+
def _validate_live_preview(self):
201+
lp = self.http_instance.live_preview
202+
if 'content_type_uid' in lp and lp['content_type_uid'] is not None:
203+
if lp['content_type_uid'] != str(self.content_type_id):
204+
self.http_instance.live_preview['enable'] = False
205+
pass

contentstack/https_connection.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,16 @@ def __init__(self, endpoint, headers, timeout, retry_strategy, live_preview):
6060
self.retry_strategy = retry_strategy
6161
self.live_preview = live_preview
6262

63+
def impl_live_preview(self):
64+
if self.live_preview['enable']:
65+
print(self.live_preview)
66+
# Get all the params from live preview and make a request,
67+
# get the data and merger it to the base response
68+
pass
69+
6370
def get(self, url):
6471
self.headers.update(user_agents())
6572
adapter = HTTPAdapter(max_retries=self.retry_strategy)
6673
self.session.mount('https://', adapter)
74+
self.impl_live_preview()
6775
return get_request(self.session, url, headers=self.headers, timeout=self.timeout)

contentstack/query.py

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -319,24 +319,31 @@ def __execute_network_call(self):
319319
self.query_params["query"] = json.dumps(self.parameters)
320320
if 'environment' in self.http_instance.headers:
321321
self.query_params['environment'] = self.http_instance.headers['environment']
322-
self.__validate_live_preview()
323322
encoded_string = parse.urlencode(self.query_params, doseq=True)
324323
url = f'{self.base_url}?{encoded_string}'
325324
if self.http_instance.live_preview['enable']:
326325
if self.http_instance.live_preview['content_type_uid'] == self.content_type_uid:
327326
_rq = self.http_instance.get(url)['entries']
328327
_preview = self.http_instance.live_preview['resp']
329328
return self._merge_preview(_rq, _preview)
329+
self._validate_live_preview()
330330
return self.http_instance.get(url)
331331

332-
def _merge_preview(self, qresp, _preview):
333-
if isinstance(qresp, dict):
334-
if 'uid' in qresp and qresp['uid'] == _preview['uid']:
335-
merged = {**qresp, **_preview} # TODO: Check merging is properly written or not
336-
else:
337-
for key in dict.keys():
338-
qresp[key] = self._merge_preview(qresp[key])
339-
elif isinstance(qresp, list):
340-
for index, it in enumerate(qresp):
341-
qresp[index] = self._merge_preview(it, _preview)
342-
return qresp
332+
def _validate_live_preview(self):
333+
lp = self.http_instance.live_preview
334+
if 'content_type_uid' in lp and lp['content_type_uid'] is not None:
335+
if lp['content_type_uid'] != str(self.content_type_uid):
336+
self.http_instance.live_preview['enable'] = False
337+
pass
338+
339+
# def _merge_preview(self, qresp, _preview):
340+
# if isinstance(qresp, dict):
341+
# if 'uid' in qresp and qresp['uid'] == _preview['uid']:
342+
# merged = {**qresp, **_preview} # TODO: Check merging is properly written or not
343+
# else:
344+
# for key in dict.keys():
345+
# qresp[key] = self._merge_preview(qresp[key])
346+
# elif isinstance(qresp, list):
347+
# for index, it in enumerate(qresp):
348+
# qresp[index] = self._merge_preview(it, _preview)
349+
# return qresp

contentstack/stack.py

Lines changed: 22 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,12 @@ def __init__(self, api_key: str, delivery_token: str, environment: str,
6262
6363
```python
6464
live_preview = {
65-
'enable': True,
65+
'enable': True,
66+
'host': 'api.contentstack.io',
6667
'authorization': 'your_management_token',
67-
'host': 'api.contentstack.com',
6868
'include_edit_tags': True,
6969
'edit_tags_type': object | str,
70-
}
70+
}
7171
```
7272
:param retry_strategy: (optional) custom retry_strategy can be set.
7373
Method to create retry_strategy: create object of Retry() and provide the
@@ -77,12 +77,10 @@ def __init__(self, api_key: str, delivery_token: str, environment: str,
7777
>>> _strategy = Retry(total=5, backoff_factor=1, status_forcelist=[408, 429])
7878
>>> import contentstack
7979
>>> stack = contentstack.Stack("api_key", "delivery_token", "environment",
80-
live_preview={enable=True, authorization='your auth token'}, retry_strategy= _strategy)
80+
live_preview={enable=True, authorization='your auth token'}, retry_strategy= _strategy)
8181
```
8282
"""
8383
logging.basicConfig(level=logging.DEBUG)
84-
if live_preview is None:
85-
live_preview = {'enable': False}
8684
self.headers = {}
8785
self._query_params = {}
8886
self.sync_param = {}
@@ -98,7 +96,6 @@ def __init__(self, api_key: str, delivery_token: str, environment: str,
9896
self.branch = branch
9997
self.retry_strategy = retry_strategy
10098
self.live_preview = live_preview
101-
10299
self._validate_stack()
103100

104101
def _validate_stack(self):
@@ -344,36 +341,24 @@ def live_preview_query(self, **kwargs):
344341
for key, value in kwargs.iteritems():
345342
print "%s = %s" % (key, value)
346343
Uses:=>
347-
live_preview_query(
348-
host='api.contentstack.io',
349-
entry_uid='your_entry_uid',
350-
hash='hashcode'
344+
live_preview_query (
345+
'enable': True,
346+
'live_preview': '#*#*#*#*#',
347+
'host': 'your_host',
348+
'content_type_uid': 'product',
349+
'entry_uid': 'your_entry_uid',
350+
'authorization': 'management_token'
351351
)
352352
"""
353-
self.live_preview.update(kwargs)
354-
self._execute_management_api()
355-
return self
356-
357-
def _execute_management_api(self):
358-
_headers, _endpoint = self._enable_live_preview()
359-
content_type_uid = self.live_preview.get("content_type_uid")
360-
_entry_uid = self.live_preview.get("entry_uid")
361-
_url = f'{_endpoint}/content_types/{content_type_uid}/entries/{_entry_uid}'
362-
import requests
363-
r = requests.get(url=_url, verify=True, headers=_headers)
364-
if r.ok:
365-
self.live_preview['resp'] = r.json()['entry']
366-
else:
367-
print(r.status_code)
353+
if self.live_preview is not None and self.live_preview['enable']:
354+
query = kwargs['live_preview']
355+
if query is not None:
356+
self.live_preview['live_preview'] = query['live_preview']
357+
else:
358+
self.live_preview['live_preview'] = 'init'
359+
360+
if 'content_type_uid' in self.live_preview and self.live_preview['content_type_uid'] is not None:
361+
self.live_preview['content_type_uid'] = query['content_type_uid']
362+
if 'entry_uid' in self.live_preview and self.live_preview['entry_uid'] is not None:
363+
self.live_preview['entry_uid'] = query['entry_uid']
368364
return self
369-
370-
def _enable_live_preview(self):
371-
if isinstance(self.live_preview, dict) and not None:
372-
_endpoint = None
373-
_local_headers = {}
374-
if 'enable' in self.live_preview and self.live_preview['enable']:
375-
_local_headers['authorization'] = self.live_preview['authorization']
376-
_host = self.live_preview['host']
377-
_endpoint = f'https://{_host}/{self.version}'
378-
_local_headers['api_key'] = self.headers['api_key']
379-
return _local_headers, _endpoint

package-lock.json

Lines changed: 10 additions & 10 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)