pymcms 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.
- pymcms/__init__.py +6 -0
- pymcms/main.py +163 -0
- pymcms-26.12.0.dist-info/METADATA +47 -0
- pymcms-26.12.0.dist-info/RECORD +7 -0
- pymcms-26.12.0.dist-info/WHEEL +5 -0
- pymcms-26.12.0.dist-info/licenses/LICENSE +21 -0
- pymcms-26.12.0.dist-info/top_level.txt +1 -0
pymcms/__init__.py
ADDED
pymcms/main.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Client helpers for the MCMS API."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import warnings
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
import yaml
|
|
8
|
+
from requests.exceptions import InvalidURL
|
|
9
|
+
|
|
10
|
+
BASE_URL = "https://crick.mcms-pro.com/api/"
|
|
11
|
+
SPECIAL_CHARACTERS = re.compile(r'[\',\.@"+=\-!#$%^&*<>?/\|}{~:]')
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class MCMSError(Exception):
|
|
15
|
+
"""Raised when the MCMS API returns an application-level error."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class McmsSession:
|
|
19
|
+
"""Authenticated session for the MCMS API."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, username, password, business_area=None, base_url=BASE_URL):
|
|
22
|
+
self.username = username
|
|
23
|
+
self.base_url = base_url
|
|
24
|
+
self.session = None
|
|
25
|
+
self.business_area = business_area
|
|
26
|
+
self.log = []
|
|
27
|
+
self.create_session(password)
|
|
28
|
+
|
|
29
|
+
def create_session(self, password):
|
|
30
|
+
"""Create a session with authentication information."""
|
|
31
|
+
if self.session is not None:
|
|
32
|
+
print("Session already exists.")
|
|
33
|
+
return
|
|
34
|
+
|
|
35
|
+
session = requests.Session()
|
|
36
|
+
session.headers.update(get_token(self.username, password))
|
|
37
|
+
self.session = session
|
|
38
|
+
self.log.append("Session created for user %s" % self.username)
|
|
39
|
+
|
|
40
|
+
def _authenticated_session(self):
|
|
41
|
+
"""Return the active HTTP session, enforcing the session invariant."""
|
|
42
|
+
if self.session is None:
|
|
43
|
+
raise RuntimeError("No MCMS session has been created.")
|
|
44
|
+
return self.session
|
|
45
|
+
|
|
46
|
+
def get_animal(self, animal_id=None, name=None, barcode=None):
|
|
47
|
+
"""Get an animal from its name, ID, or barcode.
|
|
48
|
+
|
|
49
|
+
If multiple values are provided, only the first non-``None`` value is used.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
animal_id: Numerical ID of the animal.
|
|
53
|
+
name: Name of the animal.
|
|
54
|
+
barcode: Hexadecimal barcode of the animal.
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
A dictionary with the animal information.
|
|
58
|
+
"""
|
|
59
|
+
session = self._authenticated_session()
|
|
60
|
+
if animal_id is not None:
|
|
61
|
+
rep = session.get(f"{self.base_url}animals/{animal_id}")
|
|
62
|
+
elif name is not None:
|
|
63
|
+
rep = session.get(f"{self.base_url}animals/name/{name}")
|
|
64
|
+
elif barcode is not None:
|
|
65
|
+
rep = session.get(f"{self.base_url}animals/barcode/{barcode}")
|
|
66
|
+
else:
|
|
67
|
+
raise ValueError(
|
|
68
|
+
'At least one of "animal_id", "name" or "barcode" must be provided'
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
if rep.ok and rep.status_code == 200:
|
|
72
|
+
animal = rep.json()
|
|
73
|
+
# Multiple arguments are allowed, so check that any non-primary value
|
|
74
|
+
# matches the returned entity. The ID is always the primary lookup.
|
|
75
|
+
if name is not None and animal["name"] != name:
|
|
76
|
+
raise MCMSError(f"id `{animal_id}` does not match name `{name}`")
|
|
77
|
+
if barcode is not None and animal["barcode"] != barcode:
|
|
78
|
+
raise MCMSError(
|
|
79
|
+
f"id `{animal_id}` or name `{name}` do not match barcode "
|
|
80
|
+
f"`{barcode}`"
|
|
81
|
+
)
|
|
82
|
+
return animal
|
|
83
|
+
return handle_error(rep)
|
|
84
|
+
|
|
85
|
+
def get_procedures(self, animal_names=None, animal_id=None):
|
|
86
|
+
"""Get all procedures associated with animals.
|
|
87
|
+
|
|
88
|
+
Given a list of animal names or a single animal ID, return all associated
|
|
89
|
+
procedures.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
animal_names: A list of animal names or a single animal name.
|
|
93
|
+
animal_id: A single animal ID.
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
A list of dictionaries with procedure information.
|
|
97
|
+
"""
|
|
98
|
+
session = self._authenticated_session()
|
|
99
|
+
if animal_id is not None and animal_names is not None:
|
|
100
|
+
raise ValueError(
|
|
101
|
+
"Only one of `animal_id` or `animal_names` can be provided"
|
|
102
|
+
)
|
|
103
|
+
if animal_id is not None:
|
|
104
|
+
rep = session.get(f"{self.base_url}animalprocedures/animal/{animal_id}")
|
|
105
|
+
elif animal_names is not None:
|
|
106
|
+
if isinstance(animal_names, str):
|
|
107
|
+
animal_names = [animal_names]
|
|
108
|
+
else:
|
|
109
|
+
animal_names = [str(name) for name in animal_names]
|
|
110
|
+
rep = session.post(
|
|
111
|
+
f"{self.base_url}animalprocedures",
|
|
112
|
+
data=",".join(animal_names).encode(),
|
|
113
|
+
headers={"Content-Type": "text/plain"},
|
|
114
|
+
)
|
|
115
|
+
else:
|
|
116
|
+
raise ValueError(
|
|
117
|
+
'At least one of "animal_id" or "animal_names" must be provided'
|
|
118
|
+
)
|
|
119
|
+
if rep.ok and rep.status_code == 200:
|
|
120
|
+
return rep.json()
|
|
121
|
+
return handle_error(rep)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def handle_error(rep):
|
|
125
|
+
"""Handle an API response whose status code is not 200."""
|
|
126
|
+
if rep.ok:
|
|
127
|
+
warnings.warn(
|
|
128
|
+
f"The API returned unexpected status code {rep.status_code}.",
|
|
129
|
+
stacklevel=2,
|
|
130
|
+
)
|
|
131
|
+
return rep
|
|
132
|
+
if rep.status_code == 400:
|
|
133
|
+
raise MCMSError(
|
|
134
|
+
f"Error {rep.status_code}. This entity does not exist:"
|
|
135
|
+
f"{rep.url.split('/')[-1]}"
|
|
136
|
+
)
|
|
137
|
+
if rep.status_code == 404:
|
|
138
|
+
raise InvalidURL(rep.content)
|
|
139
|
+
|
|
140
|
+
raise OSError(f"Unknown error with status code {rep.status_code}")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def parse_error(error_message):
|
|
144
|
+
"""Parse the YAML message returned by an MCMS bad request."""
|
|
145
|
+
if isinstance(error_message, bytes):
|
|
146
|
+
error_message = error_message.decode("utf8")
|
|
147
|
+
return yaml.safe_load(error_message)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def get_token(username, password, base_url=BASE_URL):
|
|
151
|
+
"""Log in and return the authorization headers for an MCMS session."""
|
|
152
|
+
try:
|
|
153
|
+
rep = requests.post(
|
|
154
|
+
f"{base_url}authenticate",
|
|
155
|
+
headers={"Accept": "*/*", "username": username, "password": password},
|
|
156
|
+
)
|
|
157
|
+
except requests.exceptions.ConnectionError as error:
|
|
158
|
+
raise requests.exceptions.ConnectionError(
|
|
159
|
+
"Cannot connect to MCMS. Are you on the institution network?"
|
|
160
|
+
) from error
|
|
161
|
+
if not rep.ok:
|
|
162
|
+
raise OSError(f"Failed to authenticate. Got an error {rep.status_code}")
|
|
163
|
+
return {"Authorization": f"Bearer {rep.json()['token']}"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pymcms
|
|
3
|
+
Version: 26.12.0
|
|
4
|
+
Summary: Python wrapper for the MCMS API
|
|
5
|
+
Author-email: Antonin Blot <antonin.blot@crick.ac.uk>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/znamlab/pymcms
|
|
8
|
+
Project-URL: Issues, https://github.com/znamlab/pymcms/issues
|
|
9
|
+
Project-URL: Source, https://github.com/znamlab/pymcms
|
|
10
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: PyYAML>=6.0
|
|
23
|
+
Requires-Dist: requests>=2.0
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# pymcms
|
|
27
|
+
|
|
28
|
+
[](https://github.com/znamlab/pymcms/actions/workflows/python-uv-ci.yml)
|
|
29
|
+
[](https://github.com/znamlab/pymcms/actions/workflows/release.yml)
|
|
30
|
+
|
|
31
|
+
Wrapper to interact with MCMS API
|
|
32
|
+
|
|
33
|
+
API is documented there: https://crick-uat.colonymanagement.org/api/swagger-ui/index.html
|
|
34
|
+
|
|
35
|
+
The current version provides only access to `get_animal` and `get_procedures`
|
|
36
|
+
|
|
37
|
+
## Development
|
|
38
|
+
|
|
39
|
+
Install the locked development environment and run the checks with [uv](https://docs.astral.sh/uv/):
|
|
40
|
+
|
|
41
|
+
```shell
|
|
42
|
+
uv sync --group dev
|
|
43
|
+
uv run ruff check .
|
|
44
|
+
uv run ruff format --check .
|
|
45
|
+
uv run ty check
|
|
46
|
+
uv run pytest
|
|
47
|
+
```
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
pymcms/__init__.py,sha256=1zbhz9WRiWo38kuawlQVTjZO-zh4TTnBMUhQpfCZjTA,162
|
|
2
|
+
pymcms/main.py,sha256=E0IkJN7lwgNRe_jz1x0T_VYNDdnGGd2yzETLdP4zgM4,5939
|
|
3
|
+
pymcms-26.12.0.dist-info/licenses/LICENSE,sha256=jLPPSkb6J16ZXZwxDQY8zs9LA1yZm1M0rZ_IFigZe-A,1071
|
|
4
|
+
pymcms-26.12.0.dist-info/METADATA,sha256=CMetp4_skfe790BoTLhWQR4Ega8Rr1mTO_ZvnvOnvGA,1732
|
|
5
|
+
pymcms-26.12.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
pymcms-26.12.0.dist-info/top_level.txt,sha256=S5KrWn8j8s9DWK00HxKuBILLZm0oEJjIwx14kjPaTkA,7
|
|
7
|
+
pymcms-26.12.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021 Znamenskiy lab
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pymcms
|