printnode-community 0.3.0__py3-none-any.whl

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.
@@ -0,0 +1,13 @@
1
+ from .gateway import Gateway
2
+ from .auth import (
3
+ ApiError,
4
+ ClientError,
5
+ Unauthorized,
6
+ TooManyRequests,
7
+ ServerError,
8
+ NetworkError,
9
+ TimeoutError,
10
+ TooManyRedirectsError,
11
+ ConnectionError,
12
+ HttpError,
13
+ RequestError)
@@ -0,0 +1,228 @@
1
+ from .model import Model, Client, Account
2
+ import json
3
+
4
+
5
+ class Accounts:
6
+
7
+ def __init__(self, auth, factory):
8
+ self._auth = auth
9
+ self._factory = factory
10
+
11
+ def get_clients(self, client_ids=None, os=None):
12
+ if os:
13
+ url = "/download/client/"+os
14
+ clients = self._factory.create_latest_download(
15
+ self._auth.get(url))
16
+ else:
17
+ client_ids = str(client_ids) if client_ids else ""
18
+ url = "/download/clients/"+client_ids
19
+ clients = self._factory.create_clients(self._auth.get(url))
20
+
21
+ return clients
22
+
23
+ def modify_client_downloads(self, client_ids, enabled):
24
+ if not isinstance(enabled, bool):
25
+ raise ValueError('Incorrect type of enabled, should be bool.')
26
+
27
+ response = self._auth.patch(
28
+ "/download/clients/"+str(client_ids),
29
+ {"enabled": enabled})
30
+
31
+ return response
32
+
33
+ def get_tag(self, tagname):
34
+ tags = self._auth.get('account/tag/'+tagname)
35
+
36
+ return tags
37
+
38
+ def modify_tag(self, tagname, tagvalue):
39
+ tags = self._auth.post('account/tag/'+tagname, tagvalue)
40
+
41
+ return tags
42
+
43
+ def delete_tag(self, tagname):
44
+ tags = self._auth.delete('account/tag/'+tagname)
45
+
46
+ return tags
47
+
48
+ def modify_account(
49
+ self,
50
+ firstname=None,
51
+ lastname=None,
52
+ password=None,
53
+ email=None,
54
+ creator_ref=None
55
+ ):
56
+ mod_data = {}
57
+ if firstname is not None:
58
+ mod_data.update({"firstname": firstname})
59
+ if lastname is not None:
60
+ mod_data.update({"lastname": lastname})
61
+ if password is not None:
62
+ mod_data.update({"password": password})
63
+ if email is not None:
64
+ mod_data.update({"email": email})
65
+ if creator_ref is not None:
66
+ mod_data.update({"creatorRef": creator_ref})
67
+ if not mod_data:
68
+ raise ValueError("No fields selected to be modified, exiting")
69
+ account_id = self._auth.patch('/account', mod_data)
70
+ return account_id
71
+
72
+ def create_account(
73
+ self,
74
+ firstname,
75
+ lastname,
76
+ email,
77
+ password,
78
+ creator_ref=None,
79
+ api_keys=None,
80
+ tags=None):
81
+
82
+ acc_data = {
83
+ "Account": {
84
+ "firstname": firstname,
85
+ "lastname": lastname,
86
+ "email": email,
87
+ "password": password}
88
+ }
89
+
90
+ if creator_ref is not None:
91
+ acc_data["Account"].update({"creatorRef": creator_ref})
92
+
93
+ if api_keys is not None:
94
+ acc_data.update({"ApiKeys": api_keys})
95
+
96
+ if tags is not None:
97
+ acc_data.update({"Tags": tags})
98
+
99
+ acc_id = self._auth.post('/account', acc_data)
100
+
101
+ return acc_id
102
+
103
+ def delete_account(
104
+ self,
105
+ ):
106
+
107
+ response = self._auth.delete("/account")
108
+
109
+ return response
110
+
111
+ def delete_api_key(
112
+ self,
113
+ api_key,
114
+ ):
115
+
116
+ response = self._auth.delete('account/apikey/'+api_key)
117
+
118
+ return response
119
+
120
+ def get_api_key(
121
+ self,
122
+ api_key
123
+ ):
124
+
125
+ response = self._auth.get("/account/apikey/"+api_key)
126
+ return response
127
+
128
+ def create_api_key(
129
+ self,
130
+ api_key,
131
+ ):
132
+ response = self._auth.post("/account/apikey/"+api_key)
133
+ return response
134
+
135
+ def get_clientkey(
136
+ self,
137
+ uuid,
138
+ version,
139
+ edition):
140
+ url = "/client/key/"+uuid+"?edition="+edition+"&version="+version
141
+ response = self._auth.get(url, {'Content-Type': 'application/json'})
142
+ return response
143
+
144
+ def _get_computer_ids(self, computer):
145
+ if isinstance(computer, int):
146
+ return [computer]
147
+ elif isinstance(computer, Computer):
148
+ return [computer.id]
149
+ elif computer is None or isinstance(computer, str):
150
+ computers = [
151
+ self._factory.create_computer(comp)
152
+ for comp in self._auth.get('/computers')]
153
+ if isinstance(computer, str):
154
+ computers = [
155
+ comp
156
+ for comp in computers
157
+ if comp.name == computer]
158
+ return [c.id for c in computers]
159
+ else:
160
+ raise TypeError('computer: "{}"'.format(type(computer)))
161
+
162
+ def _get_computer_id(self, computer):
163
+ return self._get_model_id(computer, Computer)
164
+
165
+ def _get_printer_id(self, printer):
166
+ return self._get_model_id(printer, Printer)
167
+
168
+ def _get_printjob_id(self, printjob):
169
+ return self._get_model_id(printjob, PrintJob)
170
+
171
+ def _get_model_id(self, model, model_type):
172
+ if isinstance(model, int):
173
+ return model
174
+ elif isinstance(model, model_type):
175
+ return model.id
176
+ else:
177
+ raise TypeError(str(type(model)))
178
+
179
+ def _get_printer_ids(self, printer):
180
+ if isinstance(printer, int):
181
+ return [printer]
182
+ elif isinstance(printer, Printer):
183
+ return [Printer.id]
184
+ elif printer is None or isinstance(printer, str):
185
+ printers = {
186
+ self._factory.create_printer(printer_dict)
187
+ for printer_dict in self._auth.get('/printer')}
188
+ if isinstance(printer, str):
189
+ printers = {
190
+ p for p in printers if p.name == printer}
191
+ return printers
192
+ else:
193
+ raise TypeError('printer: "{}"'.format(type(printer)))
194
+
195
+ def _is_multi_query(self, obj):
196
+ if obj is None:
197
+ return True
198
+ elif isinstance(obj, int):
199
+ return False
200
+ elif isinstance(obj, str):
201
+ return True
202
+ elif isinstance(obj, Model):
203
+ return False
204
+ else:
205
+ raise TypeError('type "{}" unsupported'.format(type(obj)))
206
+
207
+ def _get_printer_by_name(self, printer_name, computer_id=None):
208
+ assert isinstance(printer_name, str)
209
+ assert not computer_id or isinstance(computer_id, int)
210
+ printers = self.get_printers(computer=computer_id)
211
+ return [
212
+ printer
213
+ for printer in printers
214
+ if printer.name == printer_name]
215
+
216
+
217
+ class LookupFailedError(RuntimeError):
218
+
219
+ def __init__(self, obj_name, field, value):
220
+ msg = 'Failed to find a matching {} with {} of {}'.format(
221
+ obj_name,
222
+ field,
223
+ value)
224
+ super(RuntimeError, self).__init__(msg)
225
+
226
+ self.obj_name = obj_name
227
+ self.field = field
228
+ self.value = value
@@ -0,0 +1,224 @@
1
+ import re
2
+ import os
3
+ import json
4
+ import requests
5
+ import sys
6
+ from future.utils import raise_from
7
+
8
+
9
+ class Auth:
10
+
11
+ def __init__(self, url, sslcert=None, **kwargs):
12
+ self._url = url
13
+ self._sslcert = sslcert
14
+ if sslcert is not None and not os.path.isfile(sslcert):
15
+ raise FileNotFoundError(
16
+ 'sslcert file "{}" not found'.format(sslcert))
17
+ if {'email', 'password'} == set(kwargs):
18
+ self._init_from_credentials(**kwargs)
19
+ elif {'apikey'} == set(kwargs):
20
+ self._init_from_apikey(**kwargs)
21
+ elif {'clientkey'} == set(kwargs):
22
+ self._init_from_clientkey(**kwargs)
23
+ elif {'apikey', 'child_email'} == set(kwargs):
24
+ self._init_from_child_email(**kwargs)
25
+ elif {'apikey', 'child_ref'} == set(kwargs):
26
+ self._init_from_child_ref(**kwargs)
27
+ elif {'apikey', 'child_id'} == set(kwargs):
28
+ self._init_from_child_id(**kwargs)
29
+ else:
30
+ raise KeyError('incorrect constructor args combination')
31
+
32
+ def _init_from_credentials(self, email, password):
33
+ self._auth = (email, password)
34
+ self._headers = {'X-Auth-With-Account-Credentials': 'API'}
35
+
36
+ def _init_from_apikey(self, apikey):
37
+ self._auth = (apikey, '')
38
+ self._headers = {}
39
+
40
+ def _init_from_clientkey(self, clientkey):
41
+ self._auth = (clientkey, '')
42
+ self._headers = {'X-Auth-With-Client-Key': 'API'}
43
+
44
+ def _init_from_child_email(self, apikey, child_email):
45
+ self._auth = (apikey, '')
46
+ self._headers = {'X-Child-Account-By-Email': child_email}
47
+
48
+ def _init_from_child_ref(self, apikey, child_ref):
49
+ self._auth = (apikey, '')
50
+ self._headers = {'X-Child-Account-By-CreatorRef': child_ref}
51
+
52
+ def _init_from_child_id(self, apikey, child_id):
53
+ self._auth = (apikey, '')
54
+ self._headers = {'X-Child-Account-By-Id': child_id}
55
+
56
+ def get(self, endpoint, request_headers=None):
57
+ return self._request(requests.get, endpoint, None, request_headers)
58
+
59
+ def post(self, endpoint, fields=None, request_headers=None):
60
+ return self._request(requests.post, endpoint, fields, request_headers)
61
+
62
+ def patch(self, endpoint, fields=None, request_headers=None):
63
+ return self._request(requests.patch, endpoint, fields, request_headers)
64
+
65
+ def delete(self, endpoint, request_headers=None):
66
+ return self._request(requests.delete, endpoint, None, request_headers)
67
+
68
+ def _request(self, method, endpoint, fields=None, request_headers=None):
69
+ # request handling
70
+
71
+ # :param method - requests.(get/post/patch/delete)
72
+ # :param endpoint - https://api.printnode.com/(endpoint)
73
+ # :param fields - data fields to be sent with a post or patch
74
+ # :param request_headers- if a function requires an extra header or has
75
+ # custom user set headers, add them to _headers
76
+
77
+ if not endpoint.startswith('/'):
78
+ endpoint = '/' + endpoint
79
+ other_args = {}
80
+ if fields is not None:
81
+ other_args['data'] = json.dumps(fields)
82
+ headers = {}
83
+ if request_headers is not None:
84
+ headers.update(request_headers)
85
+ headers.update(self._headers)
86
+
87
+ if method == requests.patch:
88
+ headers.update({"Content-Type": "application/json"})
89
+
90
+ if self._sslcert is not None:
91
+ other_args['verify'] = self._sslcert
92
+ url = self._url + endpoint
93
+ with rewrite_requests_error():
94
+ response = method(
95
+ url=url,
96
+ auth=self._auth,
97
+ headers=headers,
98
+ **other_args)
99
+
100
+ content_type = response.headers.get('content-type')
101
+ media_type = None
102
+ if content_type is not None:
103
+ media_type = content_type.split(';', 1)[0].strip().lower()
104
+ if media_type != 'application/json':
105
+ template = 'Incorrect Content-Type "{}" for url "{}"'
106
+ raise ValueError(template.format(content_type, url))
107
+ response_obj = response.json()
108
+ if sys.version_info[0] < 3:
109
+ response_obj = self._fix_unicode(response_obj)
110
+
111
+ if 401 == response.status_code:
112
+ raise Unauthorized(response.status_code, **response_obj)
113
+ elif 429 == response.status_code:
114
+ raise TooManyRequests(response.status_code, **response_obj)
115
+ elif self._is_hundreth(4, response.status_code):
116
+ raise ClientError(response.status_code, **response_obj)
117
+ elif self._is_hundreth(5, response.status_code):
118
+ raise ServerError(response.status_code, **response_obj)
119
+ elif self._is_hundreth(2, response.status_code):
120
+ return response_obj
121
+ else:
122
+ raise Exception('status code: ' + str(response.status_code))
123
+
124
+ def _is_hundreth(self, hundreth, number):
125
+ pattern = str(hundreth) + r'\d{2,}'
126
+ return bool(re.match(pattern, str(number)))
127
+
128
+ def _fix_unicode(self, json_object):
129
+ returnvalue = json_object
130
+ if type(json_object) is dict:
131
+ returnvalue = {}
132
+ for k, v in json_object.iteritems():
133
+ if type(k) is unicode:
134
+ k = k.encode('utf-8')
135
+ if type(v) is dict or type(v) is list:
136
+ v = self._fix_unicode(v)
137
+ if type(v) is unicode:
138
+ v = v.encode('utf-8')
139
+ returnvalue.update({k: v})
140
+ if type(json_object) is list:
141
+ returnvalue = []
142
+ for x in json_object:
143
+ if type(x) is unicode:
144
+ x = x.encode('utf-8')
145
+ if type(x) is dict or type(x) is list:
146
+ x = self._fix_unicode(x)
147
+ returnvalue.append(x)
148
+ if type(json_object) is unicode:
149
+ returnvalue = json_object.encode('utf-8')
150
+ return returnvalue
151
+
152
+
153
+ class ApiError(RuntimeError):
154
+ def __init__(self, status_code, code, message, uid=None, **remaining):
155
+ super(ApiError, self).__init__('{}({}): {}'.format(
156
+ code,
157
+ status_code,
158
+ message))
159
+ self.status_code = status_code
160
+ self.code = code
161
+ self.message = message
162
+ self.uid = uid
163
+
164
+
165
+ class ClientError(ApiError):
166
+ pass
167
+
168
+
169
+ class Unauthorized(ClientError):
170
+ pass
171
+
172
+
173
+ class TooManyRequests(ClientError):
174
+ pass
175
+
176
+
177
+ class ServerError(ApiError):
178
+ pass
179
+
180
+
181
+ class NetworkError(RuntimeError):
182
+ pass
183
+
184
+
185
+ class TimeoutError(NetworkError):
186
+ pass
187
+
188
+
189
+ class TooManyRedirectsError(NetworkError):
190
+ pass
191
+
192
+
193
+ class ConnectionError(NetworkError):
194
+ pass
195
+
196
+
197
+ class HttpError(NetworkError):
198
+ pass
199
+
200
+
201
+ class RequestError(NetworkError):
202
+ pass
203
+
204
+
205
+ class rewrite_requests_error:
206
+
207
+ mapping = {
208
+ requests.Timeout: TimeoutError,
209
+ requests.TooManyRedirects: TooManyRedirectsError,
210
+ requests.HTTPError: HttpError,
211
+ requests.ConnectionError: ConnectionError}
212
+
213
+ def __enter__(self):
214
+ pass
215
+
216
+ def __exit__(self, exc_type, exc_value, traceback):
217
+ if exc_type is None:
218
+ return
219
+ exc = RequestError
220
+ for request_exc, network_exc in self.mapping.items():
221
+ if issubclass(exc_type, request_exc):
222
+ exc = network_exc
223
+ break
224
+ raise_from(exc(str(exc_value)), exc_value)