Contentstack 0.1.0__tar.gz → 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. contentstack-1.0.0/PKG-INFO +19 -0
  2. {contentstack-0.1.0 → contentstack-1.0.0}/README.md +31 -42
  3. contentstack-1.0.0/contentstack/__init__.py +13 -0
  4. contentstack-1.0.0/contentstack/asset.py +140 -0
  5. contentstack-1.0.0/contentstack/assetquery.py +119 -0
  6. contentstack-1.0.0/contentstack/basequery.py +197 -0
  7. contentstack-1.0.0/contentstack/contenttype.py +113 -0
  8. contentstack-1.0.0/contentstack/entry.py +126 -0
  9. contentstack-1.0.0/contentstack/entryqueryable.py +187 -0
  10. contentstack-1.0.0/contentstack/https_connection.py +85 -0
  11. contentstack-1.0.0/contentstack/image_transform.py +54 -0
  12. contentstack-1.0.0/contentstack/query.py +299 -0
  13. contentstack-1.0.0/contentstack/stack.py +252 -0
  14. contentstack-1.0.0/contentstack/utility.py +62 -0
  15. contentstack-1.0.0/contentstack.egg-info/PKG-INFO +19 -0
  16. {contentstack-0.1.0 → contentstack-1.0.0}/contentstack.egg-info/SOURCES.txt +8 -5
  17. contentstack-1.0.0/contentstack.egg-info/not-zip-safe +1 -0
  18. contentstack-1.0.0/contentstack.egg-info/requires.txt +1 -0
  19. contentstack-1.0.0/setup.py +47 -0
  20. contentstack-0.1.0/PKG-INFO +0 -146
  21. contentstack-0.1.0/contentstack/__init__.py +0 -29
  22. contentstack-0.1.0/contentstack/asset.py +0 -784
  23. contentstack-0.1.0/contentstack/config.py +0 -162
  24. contentstack-0.1.0/contentstack/content_type.py +0 -233
  25. contentstack-0.1.0/contentstack/entry.py +0 -1162
  26. contentstack-0.1.0/contentstack/errors.py +0 -162
  27. contentstack-0.1.0/contentstack/http_connection.py +0 -195
  28. contentstack-0.1.0/contentstack/query.py +0 -1632
  29. contentstack-0.1.0/contentstack/stack.py +0 -760
  30. contentstack-0.1.0/contentstack/utils.py +0 -34
  31. contentstack-0.1.0/contentstack.egg-info/PKG-INFO +0 -146
  32. contentstack-0.1.0/contentstack.egg-info/requires.txt +0 -2
  33. contentstack-0.1.0/setup.py +0 -89
  34. {contentstack-0.1.0 → contentstack-1.0.0}/contentstack.egg-info/dependency_links.txt +0 -0
  35. {contentstack-0.1.0 → contentstack-1.0.0}/contentstack.egg-info/top_level.txt +0 -0
  36. {contentstack-0.1.0 → contentstack-1.0.0}/setup.cfg +0 -0
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.1
2
+ Name: contentstack
3
+ Version: 1.0.0
4
+ Summary: Contentstack is a headless CMS with an API-first approach.
5
+ Home-page: https://github.com/contentstack/contentstack-python
6
+ Author: contentstack
7
+ Author-email: mshaileshr@gmail.com
8
+ License: MIT
9
+ Description: 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
10
+ Keywords: contentstack-python
11
+ Platform: UNKNOWN
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Natural Language :: English
16
+ Classifier: Programming Language :: Python :: 3.6
17
+ Classifier: Programming Language :: Python :: 3.7
18
+ Requires-Python: >=3.6
19
+ Description-Content-Type: text/markdown
@@ -1,12 +1,13 @@
1
1
  [![Contentstack](https://www.contentstack.com/docs/static/images/contentstack.png)](https://www.contentstack.com/)
2
2
 
3
+ ![Python package](https://github.com/contentstack/contentstack-python/workflows/Python%20package/badge.svg?branch=1.0.0) ![Coverage](https://raw.githubusercontent.com/contentstack/contentstack-python/c13bfddf10391924ed2323fdacf1e8914c7c857c/coverage.svg) ![pip](https://img.shields.io/badge/pip-1.0.0-blue?style=plastic) [![GitHub license](https://img.shields.io/github/license/contentstack/contentstack-python?style=plastic)](https://github.com/contentstack/contentstack-python/blob/master/LICENSE) [![GitHub stars](https://img.shields.io/github/stars/contentstack/contentstack-python?style=plastic)](https://github.com/contentstack/contentstack-python/stargazers)
4
+
3
5
  ## Python SDK for Contentstack
4
6
 
5
7
  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/).
6
8
 
7
9
  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.
8
10
 
9
-
10
11
  ### Prerequisite
11
12
 
12
13
  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).
@@ -15,67 +16,60 @@ You will need python 3 installed on your machine. You can install it from [here]
15
16
 
16
17
  To use the Contentstack Python SDK to your existing project, perform the steps given below:
17
18
 
18
- **Install contentstack pip**
19
+ ### Install contentstack pip
19
20
 
20
- ```
21
- pip install contentstack
22
- ```
21
+ pip install contentstack
23
22
 
23
+ 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
24
24
 
25
25
  ### Key Concepts for using Contentstack
26
26
 
27
27
  #### Stack
28
28
 
29
- A stack is like a container that holds the content of your app. Learn more about [Stacks](https://www.contentstack.com/docs/guide/stack).
29
+ 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).
30
30
 
31
31
  #### Content Type
32
32
 
33
- 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/guide/content-types).
33
+ 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).
34
34
 
35
35
  #### Entry
36
36
 
37
- 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/guide/content-management#working-with-entries).
37
+ 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).
38
38
 
39
39
  #### Asset
40
40
 
41
- 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/guide/content-management#working-with-assets).
41
+ 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).
42
42
 
43
43
  #### Environment
44
44
 
45
- 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/guide/environments).
46
-
47
-
45
+ 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).
48
46
 
49
47
  ### Contentstack Python SDK: 5-minute Quickstart
50
48
 
51
49
  #### Initializing your SDK
52
50
 
53
- To initialize the SDK, specify application API key, access token, and environment name of the stack as shown in the snippet given below (config is optional):
54
- ```
55
- stack = contentstack.Stack(api_key='api_key', access_token='access_token', environment='environment', config=config)
56
- ```
57
- 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.
51
+ 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:
58
52
 
53
+ stack = contentstack.Stack('api_key','delivery_token','environment')
59
54
 
55
+ 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.
60
56
 
61
57
  #### Querying content from your stack
62
58
 
63
59
  To retrieve a single entry from a content type use the code snippet given below:
64
60
 
65
- ```
66
- content_type = stack.content_type("content_type_uid")
67
- entry = content_type.entry("entry_uid")
68
- result = entry.fetch()
69
- ```
61
+ stack = contentstack.Stack('api_key','delivery_token','environment')
62
+ content_type = stack.content_type("content_type_uid")
63
+ entry = content_type.entry("entry_uid")
64
+ result = entry.fetch()
65
+
70
66
  ##### Get Multiple Entries
71
67
 
72
68
  To retrieve multiple entries of a particular content type, use the code snippet given below:
73
69
 
74
- ```
75
- //stack is an instance of Stack class
76
- query = stack.content_type("content_type_uid").query()
77
- result = query.find()
78
- ```
70
+ stack = contentstack.Stack('api_key','delivery_token','environment')
71
+ query = stack.content_type("content_type_uid").query()
72
+ result = query.find()
79
73
 
80
74
 
81
75
  ### Advanced Queries
@@ -90,32 +84,27 @@ We have introduced Image Delivery APIs that let you retrieve images and then man
90
84
 
91
85
  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/blteae40eb499811073/bltc5064f36b5855343/59e0c41ac0eddd140d5a8e3e/download?crop=300,400. There are several more parameters that you can use for your images.
92
86
 
93
- [Read Image Delivery API documentation](https://www.contentstack.com/docs/apis/image-delivery-api/).
87
+ [Read Image Delivery API documentation](https://www.contentstack.com/docs/platforms/python/api-reference/).
94
88
 
95
89
  You can use the Image Delivery API functions in this SDK as well. Here are a few examples of its usage in the SDK.
96
90
 
97
- ```
98
- //set the image quality to 100
99
- image_params = {'quality': 100}
100
- imageUrl = stack.image_transform(image_url, **image_params);
91
+ image = stack.image_transform(url, {'quality': 100}).get_url()
92
+ image = stack.image_transform(url, {'width': 100, 'height': 100}).get_url()
93
+ image = stack.image_transform(url, {'auto': 'webp'}).get_url()
101
94
 
102
- //resize the image by specifying width and height
103
- image_params = {'width': 100, 'height': 100}
104
- imageUrl = stack.image_transform(imageUrl, **image_params);
95
+ ### Using the Sync API with Python SDK
105
96
 
106
- //enable auto optimization for the image
107
- image_params = {'auto': 'webp'}
108
- imageUrl = stack.image_transform(imageUrl, **imageParams);
109
- ```
97
+ 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.
110
98
 
99
+ Read through to understand how to use the Sync API with Contentstack Python SDK.
111
100
 
101
+ [Using the Sync API with Python SDK](https://www.contentstack.com/docs/developers/python/using-the-sync-api-with-python-sdk)
112
102
 
113
103
  ### Helpful Links
114
104
 
115
105
  - [Contentstack Website](https://www.contentstack.com)
116
106
  - [Official Documentation](https://contentstack.com/docs)
117
- - [Content Delivery API Docs](https://contentstack.com/docs/apis/content-delivery-api/)
118
-
107
+ - [Content Delivery API Docs](https://www.contentstack.com/docs/developers/apis/content-delivery-api/)
119
108
 
120
109
  ### The MIT License (MIT)
121
110
 
@@ -125,4 +114,4 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
125
114
 
126
115
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
127
116
 
128
- 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.
117
+ 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.
@@ -0,0 +1,13 @@
1
+ from .entry import Entry
2
+ from .asset import Asset
3
+ from .contenttype import ContentType
4
+ from .https_connection import HTTPSConnection
5
+ from .stack import Stack
6
+ from .utility import Utils
7
+ # from contentstack import *
8
+
9
+ __author__ = 'Contentstack'
10
+ __status__ = 'debug'
11
+ __version__ = '1.0.0'
12
+ __endpoint__ = 'cdn.contentstack.io'
13
+ __email__ = 'mshaileshr@gmail.com'
@@ -0,0 +1,140 @@
1
+ r"""Assets refer to all the media files (images, videos, PDFs, audio files,
2
+ and so on) uploaded in your Contentstack repository for future use.
3
+
4
+ These files can be attached and used in multiple entries.
5
+ """
6
+
7
+ # ************* Module asset **************
8
+ # Your code has been rated at 10/10 by pylint
9
+
10
+ from urllib import parse
11
+
12
+
13
+ class Asset:
14
+ r"""Asset refer to all the media files (images, videos, PDFs, audio files, and so on)."""
15
+
16
+ def __init__(self, http_instance, uid=None):
17
+ self.http_instance = http_instance
18
+ self.__query_params = {}
19
+ self.__uid = uid
20
+ if self.__uid is None or self.__uid.strip() == 0:
21
+ raise KeyError('Please provide valid uid')
22
+ self.base_url = '{}/assets/{}'.format(self.http_instance.endpoint, self.__uid)
23
+ if 'environment' in self.http_instance.headers:
24
+ self.__query_params['environment'] = self.http_instance.headers['environment']
25
+ # self.http_instance.headers.pop('environment')
26
+
27
+ def environment(self, environment):
28
+ r"""Provide the name of the environment if you wish to retrieve the assets published
29
+ in a particular environment.
30
+
31
+ :param environment {str} - name of the environment
32
+
33
+ :return: Asset, so we can chain the call
34
+
35
+ -------------------------------
36
+ [Example]:
37
+
38
+ >>> import contentstack
39
+ >>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
40
+ >>> asset = stack.asset(uid='asset_uid')
41
+ >>> asset = asset.environment('production')
42
+ -------------------------------
43
+ """
44
+ if environment is not None or environment is str:
45
+ self.__query_params['environment'] = environment
46
+ return self
47
+
48
+ def remove_environment(self):
49
+ r"""Removes environment from the request params
50
+
51
+ :return: Asset, so we can chain the call
52
+
53
+ -------------------------------
54
+ [Example]:
55
+
56
+ >>> import contentstack
57
+ >>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
58
+ >>> asset = stack.asset(uid='asset_uid')
59
+ >>> asset = asset.remove_header()
60
+ >>> asset.fetch()
61
+ -------------------------------
62
+ """
63
+ if 'environment' in self.http_instance.headers:
64
+ self.http_instance.headers.pop('environment')
65
+ return self
66
+
67
+ def params(self, key, value):
68
+ r"""params is used to pass additional parameters to the asset query
69
+
70
+ :param key: key of the query parameter
71
+
72
+ :param value: value of the query parameter
73
+
74
+ :return: Asset, so we can chain the call
75
+
76
+ -----------------------------
77
+ Example::
78
+
79
+ >>> import contentstack
80
+ >>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
81
+ >>> asset = stack.asset(uid='asset_uid')
82
+ >>> asset = asset.params('key', 'value')
83
+ -----------------------------
84
+ """
85
+ if None in (key, value) or not isinstance(key, str):
86
+ raise KeyError('Kindly provide valid params')
87
+ self.__query_params[key] = value
88
+ return self
89
+
90
+ def relative_urls(self):
91
+ r"""Include the relative URLs of the assets in the response.
92
+
93
+ :return: Asset, so we can chain the call
94
+
95
+ ----------------------------
96
+ Example::
97
+
98
+ >>> import contentstack
99
+ >>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
100
+ >>> asset = stack.asset(uid='asset_uid')
101
+ >>> asset = asset.relative_urls()
102
+ ----------------------------
103
+ """
104
+ self.__query_params['relative_urls'] = 'true'
105
+ return self
106
+
107
+ def include_dimension(self):
108
+ r"""Include the dimensions (height and width) of the image in the response.
109
+ Supported image types: JPG, GIF, PNG, WebP, BMP, TIFF, SVG, and PSD.
110
+
111
+ :return: Asset, so we can chain the call
112
+
113
+ ----------------------------
114
+ Example::
115
+
116
+ >>> import contentstack
117
+ >>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
118
+ >>> asset = stack.asset(uid='asset_uid')
119
+ >>> asset = asset.include_dimension()
120
+ ----------------------------
121
+ """
122
+ self.__query_params['include_dimension'] = "true"
123
+ return self
124
+
125
+ def fetch(self):
126
+ r"""This call fetches the latest version of a specific asset of a particular stack.
127
+
128
+ :return: json response of asset
129
+
130
+ -----------------------------
131
+ [Example]:
132
+
133
+ >>> import contentstack
134
+ >>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
135
+ >>> asset = stack.asset(uid='asset_uid')
136
+ >>> result = asset.fetch()
137
+ ------------------------------
138
+ """
139
+ url = '{}?{}'.format(self.base_url, parse.urlencode(self.__query_params))
140
+ return self.http_instance.get(url)
@@ -0,0 +1,119 @@
1
+ r"""This call fetches the list of all the assets of a particular stack.
2
+ It also returns the content of each asset in JSON format.
3
+ You can also specify the environment of which you wish to get the assets.
4
+ """
5
+
6
+ # ************* Module assetquery **************
7
+ # Your code has been rated at 10/10 by pylint
8
+
9
+ import json
10
+ from contentstack.utility import Utils
11
+ from contentstack.basequery import BaseQuery
12
+
13
+
14
+ class AssetQuery(BaseQuery):
15
+ """
16
+ This call fetches the list of all the assets of a particular stack.
17
+ """
18
+
19
+ def __init__(self, http_instance):
20
+ super().__init__()
21
+ self.http_instance = http_instance
22
+ self.__query_params = {}
23
+ self.base_url = "{}/assets".format(self.http_instance.endpoint)
24
+ if "environment" in self.http_instance.headers:
25
+ env = self.http_instance.headers["environment"]
26
+ self.base_url = "{}?{}".format(self.base_url, "environment={}".format(env))
27
+
28
+ def environment(self, environment):
29
+ r"""Provide the name of the environment if you wish to retrieve the assets published
30
+ in a particular environment.
31
+
32
+ :param environment: environment of the stack
33
+
34
+ :return: AssetQuery - so we can chain the call
35
+
36
+ -----------------------------
37
+ [Example]:
38
+
39
+ >>> import contentstack
40
+ >>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
41
+ >>> result = stack.asset_query().environment('production').find()
42
+ ------------------------------
43
+ """
44
+ self.__query_params["environment"] = environment
45
+ return self
46
+
47
+ def version(self, version):
48
+ r"""Specify the version number of the asset that you wish to retrieve.
49
+ If the version is not specified, the details of the latest version will be retrieved.
50
+ To retrieve a specific version, keep the environment parameter blank.
51
+
52
+ :param version: version number of the asset that you wish to retrieve
53
+
54
+ :return: AssetQuery: so we can chain the call
55
+
56
+ -----------------------------
57
+ [Example]:
58
+
59
+ >>> import contentstack
60
+ >>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
61
+ >>> result = stack.asset_query().version(3).find()
62
+ ------------------------------
63
+ """
64
+ self.__query_params["version"] = version
65
+ return self
66
+
67
+ def include_dimension(self):
68
+ r"""Include the dimensions (height and width) of the image in the response.
69
+ Supported image types: JPG, GIF, PNG, WebP, BMP, TIFF, SVG, and PSD
70
+
71
+ :return: AssetQuery: so we can chain the call
72
+
73
+ -----------------------------
74
+ [Example]:
75
+
76
+ >>> import contentstack
77
+ >>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
78
+ >>> result = stack.asset_query().include_dimension().find()
79
+ ------------------------------
80
+ """
81
+ self.__query_params["include_dimension"] = "true"
82
+ return self
83
+
84
+ def relative_url(self):
85
+ r"""include the relative URLs of the assets in the response.
86
+
87
+ :return: AssetQuery: so we can chain the call
88
+
89
+ -----------------------------
90
+ [Example]:
91
+
92
+ >>> import contentstack
93
+ >>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
94
+ >>> result = stack.asset_query().relative_url().find()
95
+ ------------------------------
96
+ """
97
+ self.__query_params["relative_urls"] = "true"
98
+ return self
99
+
100
+ def find(self):
101
+ r"""This call fetches the list of all the assets of a particular stack.
102
+ It also returns the content of each asset in JSON format.
103
+ Learn more about Assets
104
+ [https://www.contentstack.com/docs/content-managers/work-with-assets].
105
+
106
+ :return: json result, List of asset object
107
+
108
+ -----------------------------
109
+ [Example]:
110
+
111
+ >>> import contentstack
112
+ >>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
113
+ >>> result = stack.asset_query().find()
114
+
115
+ """
116
+ if self.parameters is not None and len(self.parameters) > 0:
117
+ self.__query_params["query"] = json.dumps(self.parameters)
118
+ url = Utils.get_complete_url(self.base_url, self.__query_params)
119
+ return self.http_instance.get(url)
@@ -0,0 +1,197 @@
1
+ """
2
+ Missing docstring
3
+ Common Query for Entry and Assets
4
+ """
5
+ import enum
6
+
7
+
8
+ # ************* Module basequery.py **************
9
+ # Your code has been rated at 10.00/10
10
+
11
+ class QueryOperation(enum.Enum):
12
+ """
13
+ QueryOperation is enum that Provides Options to perform operation to query the result.
14
+
15
+ Available Options for QueryOperation are below.
16
+ EQUALS, NOT_EQUALS, INCLUDES, EXCLUDES, IS_LESS_THAN, IS_LESS_THAN_OR_EQUAL
17
+ IS_GREATER_THAN, IS_GREATER_THAN_OR_EQUAL, EXISTS, MATCHES
18
+
19
+ Arguments:
20
+ enum {QueryOperation} -- Type of operation to perform
21
+ """
22
+ EQUALS = ""
23
+ NOT_EQUALS = '$ne'
24
+ INCLUDES = '$in'
25
+ EXCLUDES = '$nin'
26
+ IS_LESS_THAN = '$lt'
27
+ IS_LESS_THAN_OR_EQUAL = '$lte'
28
+ IS_GREATER_THAN = '$gt'
29
+ IS_GREATER_THAN_OR_EQUAL = '$gte'
30
+ EXISTS = '$exists'
31
+ MATCHES = '$regex'
32
+
33
+
34
+ def _get_operation_value(fields):
35
+ value = fields[0] if isinstance(fields, list) and len(fields) == 1 else fields
36
+ return value
37
+
38
+
39
+ class BaseQuery:
40
+ """
41
+ Common Query class works for Query As well as Asset
42
+ """
43
+
44
+ def __init__(self):
45
+ self.parameters = {}
46
+ self.query_params = {}
47
+
48
+ def where(self, field_uid: str, query_operation: QueryOperation, fields=None):
49
+ """
50
+ Get entries containing the field values matching the condition in the query.
51
+ Arguments:
52
+ field_uid {str} -- [accept field uid for the operation]
53
+ query_operation {QueryOperation} -- Type of operation to perform
54
+ fields {list} - list of string
55
+ """
56
+ if None not in (field_uid, query_operation):
57
+ result = _get_operation_value(fields) if query_operation.name == "EQUALS" \
58
+ else {query_operation.value: fields}
59
+ self.parameters[field_uid] = result
60
+ return self
61
+
62
+ def include_count(self):
63
+ """Retrieve count and data of objects in result
64
+ Returns:
65
+ [Query] -- Query object, so you can chain this call.
66
+ ==============================
67
+ [Example:]
68
+ >>> import contentstack
69
+ >>> stack = contentstack.Stack('api_key', 'access_token', 'environment')
70
+ >>> content_type = stack.content_type('content_type_uid')
71
+ >>> query = content_type.query()
72
+ >>> query = query.include_count()
73
+ >>> result = query.find()
74
+ ==============================
75
+ """
76
+ self.query_params["include_count"] = 'true'
77
+ return self
78
+
79
+ def skip(self, skip_count: int):
80
+ """
81
+ The number of objects to skip before returning any.
82
+ skip_count No of objects to skip from returned objects
83
+ :param skip_count:
84
+ :return: self
85
+ """
86
+ self.query_params["skip"] = str(skip_count)
87
+ return self
88
+
89
+ def limit(self, limit_count: int):
90
+ """
91
+ A limit on the number of objects to return.
92
+ :param limit_count:
93
+ :return: self
94
+ """
95
+ self.query_params["skip"] = str(limit_count)
96
+ return self
97
+
98
+ def order_by_ascending(self, key: str):
99
+ """
100
+ you can sort them in the ascending order with respect to the
101
+ value of a specific field in the response body.
102
+
103
+ :param key: key on which ascending order to be implemented
104
+ :return: self
105
+ """
106
+ self.query_params["asc"] = str(key)
107
+ return self
108
+
109
+ def order_by_descending(self, key: str):
110
+ """
111
+ you can sort them in the descending order with respect to the value
112
+ of a specific field in the response body.
113
+ :param key: key on which descending order to be implemented
114
+ :return: self - Class instance, So that method chaining can be performed
115
+ """
116
+ self.query_params["desc"] = str(key)
117
+ return self
118
+
119
+ def param(self, key: str, value):
120
+ """
121
+ Adds Parameters to the to the request
122
+
123
+ Arguments:
124
+ key {str} -- Key of the parameter
125
+ value {[any]} -- Value of the parameter
126
+
127
+ Raises:
128
+ KeyError: When None found in key or value
129
+
130
+ Returns:
131
+ [self] -- instance of the class
132
+
133
+ -----------------------------------
134
+
135
+ [Example]
136
+ >>> import contentstack
137
+ >>> stack = contentstack.Stack('api_key', 'access_token', 'environment')
138
+ >>> content_type = stack.content_type('content_type_uid')
139
+ >>> query = content_type.query()
140
+ >>> query = query.param("key", "value")
141
+ >>> result = query.find()
142
+
143
+ -----------------------------------
144
+ """
145
+ if None in (key, value):
146
+ raise KeyError('Invalid key or value')
147
+ self.query_params[key] = str(value)
148
+ return self
149
+
150
+ def add_params(self, param: dict):
151
+ """
152
+ Adds Parameters to the to the request
153
+ Arguments:
154
+ param {dict} -- parameters
155
+ Returns:
156
+ [self] -- Class instance, So that method chaining can be performed
157
+ """
158
+ self.query_params.update(param)
159
+ return self
160
+
161
+ def query(self, key: str, value):
162
+ """
163
+ Adds key value pairs to the to the query parameters
164
+ Arguments:
165
+ key {str} -- key of the query param
166
+ value {any} -- value of query param
167
+ Raises:
168
+ KeyError: when key or value found None
169
+ Returns:
170
+ self-- Class instance, So that method chaining can be performed
171
+ """
172
+ if None in (key, value):
173
+ raise KeyError('Invalid key or value')
174
+ self.parameters[key] = str(value)
175
+ return self
176
+
177
+ def remove_param(self, key: str):
178
+ """
179
+ Remove provided query key from custom query if exist.
180
+ :param key {str} -- The key to be constrained
181
+ :return: self -- So that method chaining can be performed
182
+
183
+ ----------------------------------
184
+ [Example]:
185
+ >>> import contentstack
186
+ >>> stack = contentstack.Stack('api_key', 'delivery_token', 'environment')
187
+ >>> content_type = stack.content_type('content_type_uid')
188
+ >>> query = content_type.query()
189
+ >>> query = query.remove_query("query_key")
190
+ >>> result = query.find()
191
+ ----------------------------------
192
+ """
193
+ if key is None:
194
+ raise ValueError('Kindly provide valid key')
195
+ if key in self.query_params:
196
+ self.query_params.pop(key, None)
197
+ return self