• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

chift-oneapi / chift-python-sdk / 7666915815

26 Jan 2024 10:18AM UTC coverage: 98.637%. First build
7666915815

push

github

hhertoghe
reformat

3112 of 3155 relevant lines covered (98.64%)

0.99 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.51
/chift/api/client.py
1
import http.client as httplib
1✔
2
import json
1✔
3
from datetime import datetime
1✔
4

5
import requests
1✔
6
from requests.adapters import HTTPAdapter
1✔
7
from requests.packages.urllib3.util.retry import Retry
1✔
8

9
from chift.api import exceptions
1✔
10

11

12
class ChiftAuth(requests.auth.AuthBase):
1✔
13
    def __init__(self, client_id, client_secret, account_id, url_base, env_id):
1✔
14
        self.client_id = client_id
1✔
15
        self.client_secret = client_secret
1✔
16
        self.account_id = account_id
1✔
17
        self.url_base = url_base
1✔
18
        self.env_id = env_id
1✔
19

20
        self.access_token = None
1✔
21
        self.exires_at = None
1✔
22

23
    def __call__(self, request):
1✔
24
        request.headers.update(self.get_auth_header())
1✔
25
        return request
1✔
26

27
    def get_auth_header(self):
1✔
28
        return {"Authorization": f"Bearer {self.get_access_token()}"}
1✔
29

30
    def _parse_token(self, token):
1✔
31
        self.access_token = token.get("access_token")
1✔
32
        self.exires_at = datetime.fromtimestamp(token.get("expires_on"))
1✔
33

34
    def get_access_token(self):
1✔
35
        if self.access_token:
1✔
36
            if datetime.now() < self.exires_at:
1✔
37
                return self.access_token
1✔
38

39
        payload = {
1✔
40
            "clientId": self.client_id,
41
            "clientSecret": self.client_secret,
42
            "accountId": self.account_id,
43
        }
44
        if self.env_id:
1✔
45
            payload["envId"] = self.env_id
×
46
        response = requests.post(self.url_base + "/token", json=payload)
1✔
47

48
        if not response.status_code == httplib.OK:
1✔
49
            raise exceptions.ChiftException(
×
50
                f"Error while authenticating '{response.status_code}': {response.text}"
51
            )
52

53
        self._parse_token(response.json())
1✔
54

55
        return self.access_token
1✔
56

57

58
class ChiftClient:
1✔
59
    session = None
1✔
60
    access_token = None
1✔
61
    auth = None
1✔
62
    consumer_id = None
1✔
63
    connection_id = None
1✔
64
    related_chain_execution_id = None
1✔
65

66
    __instance = None
1✔
67
    __use_global = False
1✔
68

69
    def __new__(cls, **kwargs):
1✔
70
        """
71
        __use_global=True for singleton usage
72
        """
73
        if ChiftClient.__use_global:
1✔
74
            if ChiftClient.__instance is None:
×
75
                ChiftClient.__instance = object.__new__(cls)
×
76
            instance = ChiftClient.__instance
×
77
        else:
78
            instance = object.__new__(cls)
1✔
79

80
        return instance
1✔
81

82
    def __init__(self, consumer_id=None, **kwargs):
1✔
83
        from chift import (
1✔
84
            account_id,
85
            client_id,
86
            client_secret,
87
            related_chain_execution_id,
88
            url_base,
89
        )
90

91
        self.consumer_id = consumer_id
1✔
92
        self.client_id = kwargs.get("client_id") or client_id
1✔
93
        self.client_secret = kwargs.get("client_secret") or client_secret
1✔
94
        self.account_id = kwargs.get("account_id") or account_id
1✔
95
        self.url_base = kwargs.get("url_base") or url_base
1✔
96
        self.env_id = kwargs.get("env_id")
1✔
97
        self.related_chain_execution_id = (
1✔
98
            kwargs.get("related_chain_execution_id") or related_chain_execution_id
99
        )
100
        self.max_retries = kwargs.get("max_retries")
1✔
101
        self._start_session()
1✔
102

103
    def _start_session(self):
1✔
104
        if not self.session:
1✔
105
            self.session = requests.Session()
1✔
106
            self.session.auth = ChiftAuth(
1✔
107
                self.client_id,
108
                self.client_secret,
109
                self.account_id,
110
                self.url_base,
111
                self.env_id,
112
            )
113

114
            if self.max_retries:
1✔
115
                retries = Retry(
×
116
                    total=int(self.max_retries),
117
                    backoff_factor=0.1,
118
                    status_forcelist=[502],
119
                )
120
                self.session.mount("http://", HTTPAdapter(max_retries=retries))
×
121
                self.session.mount("https://", HTTPAdapter(max_retries=retries))
×
122

123
    def make_request(
1✔
124
        self, request_type, url, data=None, content_type="application/json", params=None
125
    ):
126
        if not params:
1✔
127
            params = {}
1✔
128

129
        if isinstance(data, str):
1✔
130
            data = json.loads(data)
×
131

132
        headers = {
1✔
133
            "Content-Type": content_type,
134
            "Accept": "application/json",
135
            "User-Agent": "chift-python-sdk library",
136
        }
137

138
        if self.connection_id:
1✔
139
            headers["x-chift-connectionid"] = self.connection_id
1✔
140

141
        if self.related_chain_execution_id:
1✔
142
            headers["x-chift-relatedchainexecutionid"] = self.related_chain_execution_id
×
143

144
        try:
1✔
145
            req = self.process_request(
1✔
146
                request_type, url, headers=headers, params=params, json=data
147
            )
148
        except requests.exceptions.RetryError as e:
×
149
            raise exceptions.ChiftException(
×
150
                f"After {self.max_retries} retries, the request failed."
151
            )
152

153
        if req.status_code == httplib.UNAUTHORIZED:
1✔
154
            raise exceptions.ChiftException(
×
155
                "Application authentication failed",
156
                error_code=req.status_code,
157
                detail=req.text,
158
            )
159

160
        if req.status_code == 204:
1✔
161
            return True
×
162

163
        try:
1✔
164
            result = req.json()
1✔
165
        except:
×
166
            raise exceptions.ChiftException(f"Error parsing json response: {req.text}")
×
167

168
        if isinstance(result, dict) and result.get("status") == "error":
1✔
169
            raise exceptions.ChiftException(
1✔
170
                result.get("message"),
171
                error_code=result.get("error_code"),
172
                detail=result.get("detail"),
173
            )
174
        elif not req.status_code == httplib.OK:
1✔
175
            raise exceptions.ChiftException(
×
176
                f"Error returned with status code '{req.status_code}': {req.text}"
177
            )
178
        else:
179
            return result
1✔
180

181
    def process_request(
1✔
182
        self, request_type, url_path, headers=None, params=None, json=None
183
    ):
184
        return self.session.request(
1✔
185
            request_type,
186
            self.url_base + url_path,
187
            headers=headers,
188
            params=params,
189
            json=json,
190
        )
191

192
    def get(self, *args, **kwargs):
1✔
193
        return self.make_request("GET", *args, **kwargs)
1✔
194

195
    def post(self, *args, **kwargs):
1✔
196
        return self.make_request("POST", *args, **kwargs)
1✔
197

198
    def patch(self, *args, **kwargs):
1✔
199
        return self.make_request("PATCH", *args, **kwargs)
1✔
200

201
    def delete(self, *args, **kwargs):
1✔
202
        return self.make_request("DELETE", *args, **kwargs)
1✔
203

204
    def path_builder(self, ordered_paths):
1✔
205
        if ordered_paths:
1✔
206
            return "/" + "/".join(
1✔
207
                [str(path).strip("/") for path in ordered_paths if path]
208
            )
209

210
    def delete_one(
1✔
211
        self, chift_vertical, chift_model, chift_id, params=None, extra_path=None
212
    ):
213
        url_path = self.path_builder(
1✔
214
            [
215
                "consumers" if self.consumer_id else None,
216
                self.consumer_id,
217
                chift_vertical,
218
                chift_model,
219
                chift_id,
220
                extra_path,
221
            ]
222
        )
223

224
        return self.delete(url_path, params=params)
1✔
225

226
    def get_one(
1✔
227
        self, chift_vertical, chift_model, chift_id, params=None, extra_path=None
228
    ):
229
        url_path = self.path_builder(
1✔
230
            [
231
                "consumers" if self.consumer_id else None,
232
                self.consumer_id,
233
                chift_vertical,
234
                chift_model,
235
                chift_id,
236
                extra_path,
237
            ]
238
        )
239

240
        return self.get(url_path, params=params)
1✔
241

242
    def get_all(self, chift_vertical, chift_model, params=None, extra_path=None):
1✔
243
        url_path = self.path_builder(
1✔
244
            [
245
                "consumers" if self.consumer_id else None,
246
                self.consumer_id,
247
                chift_vertical,
248
                chift_model,
249
                extra_path,
250
            ]
251
        )
252

253
        return self.get(url_path, params=params)
1✔
254

255
    def post_one(self, chift_vertical, chift_model, data, extra_path=None, params=None):
1✔
256
        url_path = self.path_builder(
1✔
257
            [
258
                "consumers" if self.consumer_id else None,
259
                self.consumer_id,
260
                chift_vertical,
261
                chift_model,
262
                extra_path,
263
            ]
264
        )
265

266
        return self.post(url_path, data=data, params=params)
1✔
267

268
    def update_one(
1✔
269
        self, chift_vertical, chift_model, chift_id, data, extra_path=None, params=None
270
    ):
271
        url_path = self.path_builder(
1✔
272
            [
273
                "consumers" if self.consumer_id else None,
274
                self.consumer_id,
275
                chift_vertical,
276
                chift_model,
277
                chift_id,
278
                extra_path,
279
            ]
280
        )
281

282
        return self.patch(url_path, data=data, params=params)
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc