flexilims 26.12.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.
flexilims/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ from flexilims.main import Flexilims, get_token
2
+ from flexilims.offline import OfflineFlexilims, download_database
flexilims/main.py ADDED
@@ -0,0 +1,564 @@
1
+ """Generic function to interface with flexilims"""
2
+
3
+ import re
4
+ import time
5
+ import warnings
6
+
7
+ import requests
8
+ from requests.auth import HTTPBasicAuth
9
+
10
+ from flexilims.utils import (
11
+ AuthenticationError,
12
+ FlexilimsError,
13
+ check_flexilims_validity,
14
+ )
15
+
16
+ BASE_URL = "https://flexylims.thecrick.org/flexilims/api/"
17
+ # Or test API
18
+ # BASE_URL = "http://clvd0-ws-u-t-41.thecrick.test:8080/flexilims/api/"
19
+ DEFAULT_TIMEOUT = 60
20
+
21
+
22
+ class Flexilims(object):
23
+ """Main class to interface with flexilims
24
+
25
+ Args:
26
+ username: username to connect to flexilims
27
+ password: password to connect to flexilims
28
+ project_id: hexadecimal id of the project to use
29
+ base_url: base url of the flexilims server
30
+ token: if you already have a token, you can pass it here
31
+ timeout: default request timeout in seconds (default: 60)
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ username,
37
+ password,
38
+ project_id=None,
39
+ base_url=BASE_URL,
40
+ token=None,
41
+ timeout=DEFAULT_TIMEOUT,
42
+ ):
43
+ assert isinstance(base_url, str), "base_url must be a string"
44
+ assert base_url.endswith("api/"), "base_url must end with 'api/'"
45
+
46
+ self.username = username
47
+ self.password = password
48
+ self.base_url = base_url
49
+ self.project_id = project_id
50
+ self.timeout = timeout
51
+ self.log = []
52
+ self.session = self.create_session(password, token=token)
53
+
54
+ def create_session(self, password, token=None):
55
+ """Create a session with authentication information"""
56
+ if hasattr(self, "session"):
57
+ print("Session already exists.")
58
+ return self.session
59
+
60
+ session = requests.Session()
61
+ if token is None:
62
+ token = get_token(
63
+ self.username, password, self.base_url, timeout=self.timeout
64
+ )
65
+
66
+ session.headers.update(token)
67
+ self.log.append("Session created for user %s" % self.username)
68
+ return session
69
+
70
+ def update_token(self, timeout=600):
71
+ """Update the token in the session"""
72
+ token = None
73
+ deadline = time.monotonic() + timeout
74
+ while token is None and time.monotonic() < deadline:
75
+ try:
76
+ token = get_token(
77
+ self.username, self.password, self.base_url, timeout=self.timeout
78
+ )
79
+ except (IOError, requests.exceptions.RequestException):
80
+ if time.monotonic() >= deadline:
81
+ break
82
+ print("Failed to get a token. Retrying in 5 seconds.")
83
+ time.sleep(min(5, max(0, deadline - time.monotonic())))
84
+ if token is None:
85
+ raise IOError("Failed to get a token. Timeout reached.")
86
+ self.session.headers.update(token)
87
+
88
+ def get(
89
+ self,
90
+ datatype=None,
91
+ project_id=None,
92
+ query_key=None,
93
+ query_value=None,
94
+ created_by=None,
95
+ id=None,
96
+ name=None,
97
+ origin_id=None,
98
+ date_created=None,
99
+ date_created_operator=None,
100
+ cross_project_entity=False,
101
+ limit=None,
102
+ offset=None,
103
+ ):
104
+ """Get all the entries of type datatype in the current project
105
+
106
+ Args:
107
+ datatype: flexilims type of the object(s)
108
+ project_id: hexadecimal id of the project. If None, will use the session
109
+ default
110
+ id: flexilims id of the object.
111
+ name: name of the object. Note that on the server, if `name` is provided,
112
+ all other query parameters are ignored.
113
+ query_key: attribute name (or sequence of attribute names) to filter the
114
+ results. Multiple attributes are combined with AND.
115
+ query_value: valid value (or sequence of values, in the same order as
116
+ `query_key`) for `query_key`.
117
+ origin_id: hexadecimal id of the origin of the object
118
+ created_by: name of the user who created the object
119
+ date_created: cutoff date. Only elements with date creation greater
120
+ (default) or lower than this date will be return (see
121
+ date_created_operator), in unix time since epoch.
122
+ date_created_operator: 'gt' or 'lt' for greater or lower than (default to
123
+ 'gt') both include exact match
124
+ cross_project_entity (bool): whether to include cross project entity in the
125
+ results (default to False)
126
+ limit (int): maximum number of results to return. If None, omitted from the
127
+ request (server defaults to 1000, which is also the max per call).
128
+ offset (int): 0-based number of results to skip for pagination (default to
129
+ None).
130
+ Returns:
131
+ a list of dictionary with one element per valid flexilimns entry.
132
+ """
133
+
134
+ if project_id is None:
135
+ project_id = self.project_id
136
+ params = dict(type=datatype, project_id=project_id)
137
+ if date_created_operator is not None:
138
+ assert date_created_operator in ("gt", "lt")
139
+ elif date_created is not None:
140
+ date_created_operator = "gt"
141
+ if cross_project_entity:
142
+ params["cross_project_entity"] = "yes"
143
+ else:
144
+ params["cross_project_entity"] = "no"
145
+ # add all non-None arguments in the list
146
+ args = (
147
+ "query_key",
148
+ "query_value",
149
+ "id",
150
+ "name",
151
+ "origin_id",
152
+ "date_created",
153
+ "date_created_operator",
154
+ "created_by",
155
+ "limit",
156
+ "offset",
157
+ )
158
+ for arg_name in args:
159
+ if locals()[arg_name] is not None:
160
+ params[arg_name] = locals()[arg_name]
161
+
162
+ return self.safe_execute(
163
+ "json", self.session.get, self.base_url + "get", params=params
164
+ )
165
+
166
+ def get_children(self, id):
167
+ """Get the children of one entry based on its hexadecimal id
168
+
169
+ Args:
170
+ id: hexadecimal id of the parent object
171
+ """
172
+ return self.safe_execute(
173
+ "json", self.session.get, self.base_url + "get-children", params=dict(id=id)
174
+ )
175
+
176
+ def get_project_info(self):
177
+ """Get the list of existing project and their properties
178
+
179
+ Returns:
180
+ proj_list (list of dict): a list with one dictionary per project
181
+ """
182
+ return self.safe_execute("json", self.session.get, self.base_url + "projects")
183
+
184
+ def update_one(
185
+ self,
186
+ id,
187
+ datatype,
188
+ origin_id=None,
189
+ name=None,
190
+ attributes=None,
191
+ strict_validation=True,
192
+ allow_nulls=True,
193
+ project_id=None,
194
+ ):
195
+ """Update one existing entity
196
+
197
+ Args:
198
+ id: hexadecimal id of the entity to update on flexilims
199
+ datatype: entity type on flexilims, used to find the entity to update
200
+ origin_id: (optional) new hexadecimal id of the origin for this entity
201
+ name: (optional) new name for this entity. Must be unique
202
+ attributes: (optional) dictionary of attributes to update the entity
203
+ strict_validation: (True by default) if True, check that all attributes are
204
+ defined in the lab settings
205
+ allow_nulls: (True by default) if True, an attribute set to "" or '' will be
206
+ set to null, if False, such values will be ignored and
207
+ not updated.
208
+ Note that required attributes cannot be set to None.
209
+ project_id: deprecated and ignored (`PUT /update-one` does not accept
210
+ `project_id`).
211
+
212
+ Returns: reply from flexilims
213
+ """
214
+ if project_id is not None:
215
+ warnings.warn(
216
+ "`project_id` is deprecated in `update_one` and ignored by the server.",
217
+ DeprecationWarning,
218
+ stacklevel=2,
219
+ )
220
+
221
+ params = dict(type=datatype, id=id)
222
+ json_data = {}
223
+ if name is not None:
224
+ json_data["name"] = name
225
+ if origin_id is not None:
226
+ json_data["origin_id"] = origin_id
227
+ if attributes is not None:
228
+ json_data["attributes"] = check_flexilims_validity(attributes)
229
+
230
+ address = "update-one"
231
+ # add flags
232
+ if strict_validation:
233
+ params["strict_validation"] = "true"
234
+ if allow_nulls:
235
+ params["allow_nulls"] = "true"
236
+ return self.safe_execute(
237
+ "json",
238
+ self.session.put,
239
+ self.base_url + address,
240
+ params=params,
241
+ json=json_data,
242
+ )
243
+
244
+ def update_many(
245
+ self,
246
+ datatype,
247
+ update_key,
248
+ update_value,
249
+ query_key=None,
250
+ query_value=None,
251
+ project_id=None,
252
+ strict_validation=False,
253
+ allow_non_str=False,
254
+ ):
255
+ """Update many existing entity
256
+
257
+ Args:
258
+ datatype: entity type on flexilims, used to find the entity to update
259
+ update_key: attribute that you want to update
260
+ update_value: new value for the attributes (must be a str unless
261
+ `allow_non_str=True`, as the `update-many` endpoint only stores strings)
262
+ query_key (optional): attribute to select which entries to update
263
+ query_value (optional): valid value for query_key
264
+ project_id (optional): hexadecimal project id. Use self.project if None.
265
+ strict_validation: (False by default) if True, check that all attributes
266
+ are defined in the lab settings (note: not listed in the
267
+ current `update-many` API docs)
268
+ allow_non_str: (False by default) if False, raise `TypeError` if any
269
+ provided argument is not a `str`. Set to True to bypass this check.
270
+
271
+ Returns: reply from flexilims
272
+ """
273
+
274
+ if project_id is None:
275
+ project_id = self.project_id
276
+ if not allow_non_str:
277
+ if not isinstance(update_value, str):
278
+ raise TypeError(
279
+ "`update_value` must be a str in `update_many` "
280
+ f"(got {type(update_value).__name__}). The `update-many` endpoint "
281
+ "only stores string values; pass `allow_non_str=True` to bypass "
282
+ "this check."
283
+ )
284
+ if query_value is not None and not isinstance(query_value, str):
285
+ raise TypeError(
286
+ "`query_value` must be a str in `update_many` "
287
+ f"(got {type(query_value).__name__}). The `update-many` endpoint "
288
+ "only matches string-typed attributes; pass `allow_non_str=True` "
289
+ "to bypass this check."
290
+ )
291
+ for arg_name, arg_val in (
292
+ ("datatype", datatype),
293
+ ("update_key", update_key),
294
+ ):
295
+ if not isinstance(arg_val, str):
296
+ raise TypeError(
297
+ f"`{arg_name}` must be a str in `update_many` "
298
+ f"(got {type(arg_val).__name__}); pass `allow_non_str=True` "
299
+ "to bypass this check."
300
+ )
301
+ for arg_name, arg_val in (
302
+ ("query_key", query_key),
303
+ ("project_id", project_id),
304
+ ):
305
+ if arg_val is not None and not isinstance(arg_val, str):
306
+ raise TypeError(
307
+ f"`{arg_name}` must be a str in `update_many` "
308
+ f"(got {type(arg_val).__name__}); pass `allow_non_str=True` "
309
+ "to bypass this check."
310
+ )
311
+ if update_value == "":
312
+ raise ValueError(
313
+ "`update_value` cannot be an empty string in `update_many` "
314
+ "(rejected by the server); use `update_one()` to clear attributes "
315
+ "to None."
316
+ )
317
+ for n, w in zip(["update_key", "query_key"], [update_key, query_key]):
318
+ if isinstance(w, str) and (w.lower() != w):
319
+ warnings.warn(
320
+ f"`{n}` ({w!r}) is not lowercase. Attributes created by `post()` "
321
+ "are stored lowercase, so `update_many()` will create or match "
322
+ f"a separate {w!r} attribute.",
323
+ UserWarning,
324
+ stacklevel=2,
325
+ )
326
+ cleaned = check_flexilims_validity({update_key: update_value})
327
+ params = dict(
328
+ type=datatype,
329
+ project_id=project_id,
330
+ update_key=update_key,
331
+ update_value=cleaned[update_key],
332
+ )
333
+ if query_key is not None:
334
+ params["query_key"] = query_key
335
+ if query_value is not None:
336
+ params["query_value"] = query_value
337
+
338
+ address = "update-many"
339
+ if strict_validation:
340
+ params["strict_validation"] = "true"
341
+
342
+ return self.safe_execute(
343
+ "content", self.session.put, self.base_url + address, params=params
344
+ )
345
+
346
+ def post(
347
+ self,
348
+ datatype,
349
+ name,
350
+ attributes,
351
+ project_id=None,
352
+ origin_id=None,
353
+ strict_validation=True,
354
+ ):
355
+ """Create a new entry in the database
356
+
357
+ Args:
358
+ datatype: entity type on flexilims
359
+ name: new name for this entity. Must be unique
360
+ attributes: dictionary of attributes to update the entity. Any
361
+ mangodb-compatible element (including nested dictionary) is
362
+ supported
363
+ project_id: hexadecimal project id. Use self.project if None.
364
+ origin_id: (optional) hexadecimal id of the origin for this entity
365
+ strict_validation: (True by default) if True, check that all attributes are
366
+ defined in the lab settings
367
+
368
+ Returns: reply from flexilims
369
+ """
370
+
371
+ if project_id is None:
372
+ project_id = self.project_id
373
+ assert isinstance(project_id, str)
374
+ assert isinstance(attributes, dict)
375
+
376
+ # Flexilims cannot handle None value for now
377
+ # requests refuses invalid json, so no NaNs either
378
+ attributes = check_flexilims_validity(attributes)
379
+
380
+ json_data = dict(
381
+ type=datatype, name=name, project_id=project_id, attributes=attributes
382
+ )
383
+ if origin_id is not None:
384
+ json_data["origin_id"] = origin_id
385
+
386
+ address = "save"
387
+ params = {"strict_validation": "true"} if strict_validation else None
388
+
389
+ return self.safe_execute(
390
+ "json",
391
+ self.session.post,
392
+ self.base_url + address,
393
+ params=params,
394
+ json=json_data,
395
+ )
396
+
397
+ def safe_execute(self, mode, function, *args, **kwargs):
398
+ """Execute a function and update the token if needed
399
+
400
+ Args:
401
+ mode: 'json' or 'content' to return the json or the content of the response
402
+ function: function to execute
403
+ *args: arguments to pass to the function
404
+ **kwargs: keyword arguments to pass to the function
405
+ Returns:
406
+ json or content of the response
407
+ """
408
+ if mode not in ("json", "content"):
409
+ raise ValueError("mode must be 'json' or 'content'")
410
+ kwargs.setdefault("timeout", self.timeout)
411
+ try:
412
+ rep = function(*args, **kwargs)
413
+ handled = self.handle_error(rep)
414
+ except AuthenticationError:
415
+ # try to update the token and retry
416
+ self.update_token()
417
+ rep = function(*args, **kwargs)
418
+ handled = self.handle_error(rep)
419
+ if handled is not None:
420
+ return handled
421
+ if mode == "json":
422
+ return rep.json()
423
+ return rep.content.decode("utf8")
424
+
425
+ def delete(self, id=None, datatype=None, origin_name=None, project_id=None):
426
+ """Delete an entity by id, or delete direct children by type and origin name.
427
+
428
+ Supports two mutually exclusive modes:
429
+ - By `id`: delete the single entity with that hexadecimal id.
430
+ - By `datatype` and `origin_name` (plus `project_id`, defaulting to
431
+ `self.project_id`): delete all direct children of type `datatype` whose
432
+ origin has name `origin_name` (not recursive).
433
+
434
+ Args:
435
+ id: hexadecimal id of the entity to delete
436
+ datatype: entity type to delete (used with `origin_name`)
437
+ origin_name: name of the parent/origin entity (used with `datatype`)
438
+ project_id: hexadecimal project id (used with `datatype` and `origin_name`;
439
+ defaults to `self.project_id`)
440
+
441
+ Returns:
442
+ str: reply message from flexilims
443
+ """
444
+ by_id = id is not None
445
+ by_origin = (
446
+ datatype is not None or origin_name is not None or project_id is not None
447
+ )
448
+ if by_id and by_origin:
449
+ raise ValueError(
450
+ "Provide either `id` or (`datatype`, `origin_name`, `project_id`), "
451
+ "not both."
452
+ )
453
+ if by_id:
454
+ if not isinstance(id, str) or not id.strip():
455
+ raise ValueError("`id` must be a non-empty string.")
456
+ params = dict(id=id)
457
+ elif datatype is not None and origin_name is not None:
458
+ if not isinstance(datatype, str) or not datatype.strip():
459
+ raise ValueError("`datatype` must be a non-empty string.")
460
+ if not isinstance(origin_name, str) or not origin_name.strip():
461
+ raise ValueError("`origin_name` must be a non-empty string.")
462
+ if project_id is None:
463
+ project_id = self.project_id
464
+ if not isinstance(project_id, str) or not project_id.strip():
465
+ raise ValueError(
466
+ "`project_id` must be a non-empty string (provided or set on the "
467
+ "session) when deleting by `datatype` and `origin_name`."
468
+ )
469
+ params = dict(project_id=project_id, type=datatype, origin_name=origin_name)
470
+ else:
471
+ raise ValueError(
472
+ "Provide either `id` or both `datatype` and `origin_name`."
473
+ )
474
+ return self.safe_execute(
475
+ "content", self.session.delete, self.base_url + "delete", params=params
476
+ )
477
+
478
+ def handle_error(self, rep):
479
+ """handles responses that have a status code != 200"""
480
+ if rep.status_code == 200:
481
+ return
482
+ # error handling:
483
+ if rep.ok:
484
+ warnings.warn(
485
+ "Warning. Seems ok but I had an unknown status code %s. "
486
+ "Will return the response object without interpreting it; "
487
+ "see response.json() to (hopefully) get the data." % rep.status_code
488
+ )
489
+ return rep
490
+ if rep.status_code == 400:
491
+ error_dict = parse_error(rep.content)
492
+ raise IOError("Error %d: %s" % (rep.status_code, error_dict["message"]))
493
+ if rep.status_code == 404:
494
+ url = getattr(rep, "url", None) or self.base_url
495
+ raise IOError("Page not found: %s" % url)
496
+ if rep.status_code in (401, 403):
497
+ raise AuthenticationError("Forbidden. Are you logged in?")
498
+ msg = ""
499
+ content = getattr(rep, "content", b"")
500
+ if content:
501
+ parsed = parse_error(content)["message"].strip()
502
+ if parsed:
503
+ if len(parsed) > 500:
504
+ parsed = parsed[:500] + "..."
505
+ msg = f": {parsed}"
506
+ raise IOError(f"Unknown error with status code {rep.status_code}{msg}")
507
+
508
+ @property
509
+ def project_id(self):
510
+ return self._project_id
511
+
512
+ @project_id.setter
513
+ def project_id(self, value):
514
+ if value is not None:
515
+ value = str(value)
516
+ if not re.fullmatch(r"[0-9a-fA-F]{24}", value):
517
+ raise FlexilimsError(
518
+ "project_id must be a 24-character hexadecimal string. Got %s"
519
+ % value
520
+ )
521
+ self._project_id = value
522
+
523
+
524
+ def parse_error(error_message):
525
+ """Parse the error message from flexilims bad request
526
+
527
+ The messages are html pages with a bold "Type", "Message" and "Description" fields
528
+ """
529
+ if isinstance(error_message, bytes):
530
+ error_message = error_message.decode("utf8", errors="replace")
531
+ regexp = (
532
+ ".*<b>Type</b>(.*)</p><p><b>Message</b>(.*)</p><p><b>Description</b>(.*)</p>"
533
+ )
534
+ m = re.search(pattern=regexp, string=error_message, flags=re.DOTALL)
535
+ if m is None:
536
+ # Not the expected html page. Return the raw message rather than crashing so
537
+ # that callers still get an IOError carrying what the server said.
538
+ return {"type": "unknown", "message": error_message, "description": ""}
539
+ return {name: v for name, v in zip(("type", "message", "description"), m.groups())}
540
+
541
+
542
+ def get_token(username, password, base_url=BASE_URL, timeout=DEFAULT_TIMEOUT):
543
+ """Login to the database and create headers with the proper token"""
544
+ try:
545
+ rep = requests.post(
546
+ base_url + "authenticate",
547
+ auth=HTTPBasicAuth(username, password),
548
+ timeout=timeout,
549
+ )
550
+ except requests.exceptions.ConnectionError:
551
+ raise requests.exceptions.ConnectionError(
552
+ "Cannot connect to flexilims. Are you on the Crick network?"
553
+ )
554
+ if rep.ok:
555
+ token = rep.text
556
+ elif rep.status_code in (401, 403):
557
+ raise AuthenticationError(
558
+ "Failed to authenticate. Got an error %d" % rep.status_code
559
+ )
560
+ else:
561
+ raise IOError("Failed to authenticate. Got an error %d" % rep.status_code)
562
+
563
+ headers = {"Authorization": "Bearer %s" % token}
564
+ return headers