-
Notifications
You must be signed in to change notification settings - Fork 21
/
frappeclient.py
360 lines (295 loc) · 9.53 KB
/
frappeclient.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
"""
Simple Frappe-like Python wrapper for Frappe REST API. Source: https://github.com/frappe/frappe-client.
The MIT License (MIT)
Copyright (c) 2014 Web Notes Technologies Pvt. Ltd.
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:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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.
"""
import requests
import json
from urllib.parse import quote
from base64 import b64encode
from io import StringIO
class AuthError(Exception):
pass
class FrappeException(Exception):
pass
class NotUploadableException(FrappeException):
def __init__(self, doctype):
self.message = "The doctype `{1}` is not uploadable, so you can't download the template".format(
doctype
)
class FrappeClient(object):
def __init__(
self,
url=None,
username=None,
password=None,
api_key=None,
api_secret=None,
verify=True,
):
self.headers = dict(Accept="application/json")
self.session = requests.Session()
self.can_download = []
self.verify = verify
self.url = url
if username and password:
self.login(username, password)
if api_key and api_secret:
self.authenticate(api_key, api_secret)
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
self.logout()
def login(self, username, password):
r = self.session.post(
self.url,
data={"cmd": "login", "usr": username, "pwd": password},
verify=self.verify,
headers=self.headers,
)
if r.json().get("message") == "Logged In":
self.can_download = []
return r.json()
else:
raise AuthError
def authenticate(self, api_key, api_secret):
token = b64encode(f"{api_key}:{api_secret}")
auth_header = {"Authorization": f"Basic {token}"}
self.session.headers.update(auth_header)
def logout(self):
self.session.get(
self.url,
params={
"cmd": "logout",
},
)
def get_list(
self,
doctype,
fields='"*"',
filters=None,
limit_start=0,
limit_page_length=0,
order_by=None,
):
"""Returns list of records of a particular type"""
if not isinstance(fields, str):
fields = json.dumps(fields)
params = {"fields": fields}
if filters:
params["filters"] = json.dumps(filters)
if limit_page_length:
params["limit_start"] = limit_start
params["limit_page_length"] = limit_page_length
if order_by:
params["order_by"] = order_by
res = self.session.get(
f"{self.url}/api/resource/{doctype}",
params=params,
verify=self.verify,
headers=self.headers,
)
return self.post_process(res)
def insert(self, doc):
"""Insert a document to the remote server
:param doc: A dict or Document object to be inserted remotely"""
res = self.session.post(
f"{self.url}/api/resource/" + quote(doc.get("doctype")),
data={"data": json.dumps(doc)},
)
return self.post_process(res)
def insert_many(self, docs):
"""Insert multiple documents to the remote server
:param docs: List of dict or Document objects to be inserted in one request"""
return self.post_request({"cmd": "frappe.client.insert_many", "docs": docs})
def update(self, doc):
"""Update a remote document
:param doc: dict or Document object to be updated remotely. `name` is mandatory for this"""
url = f"{self.url}/api/resource/{quote(doc.get('doctype'))}/{quote(doc.get('name'))}"
res = self.session.put(url, data={"data": json.dumps(doc)})
return self.post_process(res)
def bulk_update(self, docs):
"""Bulk update documents remotely
:param docs: List of dict or Document objects to be updated remotely (by `name`)"""
return self.post_request(
{"cmd": "frappe.client.bulk_update", "docs": json.dumps(docs)}
)
def delete(self, doctype, name):
"""Delete remote document by name
:param doctype: `doctype` to be deleted
:param name: `name` of document to be deleted"""
return self.post_request(
{"cmd": "frappe.client.delete", "doctype": doctype, "name": name}
)
def submit(self, doclist):
"""Submit remote document
:param doc: dict or Document object to be submitted remotely"""
return self.post_request(
{"cmd": "frappe.client.submit", "doclist": json.dumps(doclist)}
)
def get_value(self, doctype, fieldname=None, filters=None):
return self.get_request(
{
"cmd": "frappe.client.get_value",
"doctype": doctype,
"fieldname": fieldname or "name",
"filters": json.dumps(filters),
}
)
def set_value(self, doctype, docname, fieldname, value):
return self.post_request(
{
"cmd": "frappe.client.set_value",
"doctype": doctype,
"name": docname,
"fieldname": fieldname,
"value": value,
}
)
def cancel(self, doctype, name):
return self.post_request(
{"cmd": "frappe.client.cancel", "doctype": doctype, "name": name}
)
def get_doc(self, doctype, name="", filters=None, fields=None):
"""Returns a single remote document
:param doctype: DocType of the document to be returned
:param name: (optional) `name` of the document to be returned
:param filters: (optional) Filter by this dict if name is not set
:param fields: (optional) Fields to be returned, will return everythign if not set"""
params = {}
if filters:
params["filters"] = json.dumps(filters)
if fields:
params["fields"] = json.dumps(fields)
res = self.session.get(
f"{self.url}/api/resource/{doctype}/{name}", params=params
)
return self.post_process(res)
def rename_doc(self, doctype, old_name, new_name):
"""Rename remote document
:param doctype: DocType of the document to be renamed
:param old_name: Current `name` of the document to be renamed
:param new_name: New `name` to be set"""
params = {
"cmd": "frappe.client.rename_doc",
"doctype": doctype,
"old_name": old_name,
"new_name": new_name,
}
return self.post_request(params)
def get_pdf(self, doctype, name, print_format="Standard", letterhead=True):
response = self.session.get(
f"{self.url}/api/method/frappe.templates.pages.print.download_pdf",
params={
"doctype": doctype,
"name": name,
"format": print_format,
"no_letterhead": int(not bool(letterhead)),
},
stream=True,
)
return self.post_process_file_stream(response)
def get_html(self, doctype, name, print_format="Standard", letterhead=True):
response = self.session.get(
f"{self.url}/print",
params={
"doctype": doctype,
"name": name,
"format": print_format,
"no_letterhead": int(not bool(letterhead)),
},
stream=True,
)
return self.post_process_file_stream(response)
def __load_downloadable_templates(self):
self.can_download = self.get_api(
"frappe.core.page.data_import_tool.data_import_tool.get_doctypes"
)
def get_upload_template(self, doctype, with_data=False):
if not self.can_download:
self.__load_downloadable_templates()
if doctype not in self.can_download:
raise NotUploadableException(doctype)
request = self.session.get(
f"{self.url}/api/method/frappe.core.page.data_import_tool.exporter.get_template",
params={
"doctype": doctype,
"parent_doctype": doctype,
"with_data": "Yes" if with_data else "No",
"all_doctypes": "Yes",
},
)
return self.post_process_file_stream(request)
def get_api(self, method, params=None):
if params is None:
params = {}
res = self.session.get(f"{self.url}/api/method/{method}/", params=params)
return self.post_process(res)
def post_api(self, method, params=None):
if params is None:
params = {}
res = self.session.post(f"{self.url}/api/method/{method}/", params=params)
return self.post_process(res)
def get_request(self, params):
res = self.session.get(self.url, params=self.preprocess(params))
res = self.post_process(res)
return res
def post_request(self, data):
res = self.session.post(self.url, data=self.preprocess(data))
res = self.post_process(res)
return res
def preprocess(self, params):
"""convert dicts, lists to json"""
for key, value in params.iteritems():
if isinstance(value, (dict, list)):
params[key] = json.dumps(value)
return params
def post_process(self, response):
try:
rjson = response.json()
except ValueError:
print(response.text)
raise
if rjson and ("exc" in rjson) and rjson["exc"]:
raise FrappeException("\n".join(json.loads(rjson["exc"])))
if "message" in rjson:
return rjson["message"]
elif "data" in rjson:
return rjson["data"]
else:
return None
def post_process_file_stream(self, response):
if response.ok:
output = StringIO()
for block in response.iter_content(1024):
output.write(block)
return output
else:
try:
rjson = response.json()
except ValueError:
print(response.text)
raise
if rjson and ("exc" in rjson) and rjson["exc"]:
raise FrappeException(rjson["exc"])
if "message" in rjson:
return rjson["message"]
elif "data" in rjson:
return rjson["data"]
else:
return None