pysengard 0.1.0__tar.gz

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,109 @@
1
+ name: Publish to PyPI
2
+
3
+ # Déclenché par le push d'un tag SemVer, ex. : 1.2.3, 1.2.3-rc.1
4
+ on:
5
+ push:
6
+ tags:
7
+ - '[0-9]+.[0-9]+.[0-9]+'
8
+ - '[0-9]+.[0-9]+.[0-9]+-*'
9
+
10
+ permissions:
11
+ contents: read
12
+
13
+ concurrency:
14
+ group: publish-${{ github.ref }}
15
+ cancel-in-progress: false
16
+
17
+ jobs:
18
+ validate:
19
+ name: Validate tag
20
+ runs-on: ubuntu-latest
21
+ outputs:
22
+ version: ${{ steps.version.outputs.version }}
23
+ steps:
24
+ - uses: actions/checkout@v5
25
+ with:
26
+ fetch-depth: 0
27
+
28
+ - name: Check tag is strict SemVer
29
+ id: version
30
+ run: |
31
+ TAG="${GITHUB_REF_NAME}"
32
+ SEMVER='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?$'
33
+ if ! [[ "$TAG" =~ $SEMVER ]]; then
34
+ echo "::error::Le tag '$TAG' ne respecte pas SemVer (attendu : MAJOR.MINOR.PATCH[-prerelease])"
35
+ exit 1
36
+ fi
37
+ echo "version=${TAG}" >> "$GITHUB_OUTPUT"
38
+
39
+ - name: Check tagged commit is on main
40
+ run: |
41
+ git fetch origin main
42
+ if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then
43
+ echo "::error::Le commit tagué ($GITHUB_SHA) n'appartient pas à la branche main"
44
+ exit 1
45
+ fi
46
+
47
+ - uses: astral-sh/setup-uv@v6
48
+
49
+ - name: Check tag matches package version
50
+ env:
51
+ TAG_VERSION: ${{ steps.version.outputs.version }}
52
+ run: |
53
+ PKG_VERSION=$(sed -nE "s/^__version__ = ['\"]([^'\"]+)['\"]/\1/p" src/pysengard/_version.py)
54
+ # Comparaison après normalisation PEP 440 (1.0.0-rc.1 == 1.0.0rc1)
55
+ uvx --from packaging python -c "
56
+ import sys
57
+ from packaging.version import Version
58
+ tag, pkg = Version('$TAG_VERSION'), Version('$PKG_VERSION')
59
+ if tag != pkg:
60
+ sys.exit(f'::error::Le tag ({tag}) ne correspond pas à __version__ ({pkg}) dans src/pysengard/_version.py')
61
+ print(f'Version OK : {pkg}')
62
+ "
63
+
64
+ test:
65
+ name: Lint & tests
66
+ needs: validate
67
+ runs-on: ubuntu-latest
68
+ strategy:
69
+ matrix:
70
+ python-version: ['3.10', '3.11', '3.12', '3.13']
71
+ steps:
72
+ - uses: actions/checkout@v5
73
+ - uses: astral-sh/setup-uv@v6
74
+ with:
75
+ python-version: ${{ matrix.python-version }}
76
+ - run: uv sync --locked
77
+ - run: uv run ruff check .
78
+ - run: uv run ruff format --check .
79
+ - run: uv run pytest
80
+
81
+ build:
82
+ name: Build distributions
83
+ needs: test
84
+ runs-on: ubuntu-latest
85
+ steps:
86
+ - uses: actions/checkout@v5
87
+ - uses: astral-sh/setup-uv@v6
88
+ - run: uv build
89
+ - uses: actions/upload-artifact@v4
90
+ with:
91
+ name: dist
92
+ path: dist/
93
+ if-no-files-found: error
94
+
95
+ publish:
96
+ name: Publish to PyPI
97
+ needs: [validate, build]
98
+ runs-on: ubuntu-latest
99
+ environment:
100
+ name: pypi
101
+ url: https://pypi.org/project/pysengard/${{ needs.validate.outputs.version }}/
102
+ permissions:
103
+ id-token: write # Trusted Publishing (OIDC), aucun token PyPI à stocker
104
+ steps:
105
+ - uses: actions/download-artifact@v4
106
+ with:
107
+ name: dist
108
+ path: dist/
109
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,10 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ .coverage
10
+ htmlcov/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yannick Lemaréchal
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,140 @@
1
+ Metadata-Version: 2.5
2
+ Name: pysengard
3
+ Version: 0.1.0
4
+ Summary: Python client for the Isengard REST API (v1)
5
+ Author: Yannick Lemaréchal
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
10
+ Classifier: Typing :: Typed
11
+ Requires-Python: >=3.10
12
+ Requires-Dist: httpx>=0.27
13
+ Requires-Dist: pydantic>=2.6
14
+ Description-Content-Type: text/markdown
15
+
16
+ # pysengard
17
+
18
+ Python client for the **Isengard REST API v1** (`/api/v1/`): projects, albums and sub-albums, studies and series, album
19
+ copy and duplication, album DICOMweb tokens and album members.
20
+
21
+ The DICOMweb API (`/api/dicomweb/`: QIDO-RS, WADO-RS, STOW-RS) is not covered: use a DICOMweb client (for example
22
+ [dicomweb-client](https://github.com/ImagingDataCommons/dicomweb-client)) with an album token created by `pysengard`.
23
+
24
+ ## Installation
25
+
26
+ Python 3.10 or newer.
27
+
28
+ ```bash
29
+ pip install pysengard
30
+ # or, in a uv project
31
+ uv add pysengard
32
+ ```
33
+
34
+ ## Authentication
35
+
36
+ Every call requires a **personal token**, created on Isengard's *Profile → Tokens* page (or the access token of an
37
+ application that signs its users in with Isengard via OpenID Connect, limited by its scopes).
38
+
39
+ ```python
40
+ from pysengard import Isengard
41
+
42
+ isengard = Isengard('https://isengard.example.org', token='…')
43
+ ```
44
+
45
+ Without arguments, the client reads the `ISENGARD_URL` and `ISENGARD_TOKEN` environment variables:
46
+
47
+ ```python
48
+ isengard = Isengard() # or Isengard.from_env()
49
+ print(isengard.me().username)
50
+ ```
51
+
52
+ The URL can be either the site's or the API's (`…/api/v1`). Options: `timeout`, `verify` (TLS certificate), `max_retries`
53
+ (retries of a request rejected with 429 by the rate limit), `headers`, `transport` (httpx).
54
+
55
+ ## Usage
56
+
57
+ ```python
58
+ import datetime as dt
59
+
60
+ from pysengard import AlbumCategory, ConflictError, Isengard, Permission
61
+
62
+ with Isengard() as isengard:
63
+ # Visible projects and albums: list() returns one page, iter() walks through all pages.
64
+ page = isengard.projects.list(limit=20)
65
+ print(page.count, [project.name for project in page])
66
+
67
+ for album in isengard.albums.iter(permissions=[Permission.CAN_CREATE_TOKEN]):
68
+ print(album.album_id, album.name, album.series_count)
69
+
70
+ album = isengard.albums.get('6DgJD3F7')
71
+
72
+ # Studies and series of an album, with the filters of its page.
73
+ for study in isengard.albums.iter_studies(album.album_id, patient_name='john doe', modalities=['CT', 'MR']):
74
+ for series in isengard.albums.study_series(album.album_id, study.uid):
75
+ print(study.patient_id, series.modality, series.uid)
76
+
77
+ # Search across all visible albums (not paginated: has_more suggests narrowing the query).
78
+ result = isengard.studies.search('doe', date_from=dt.date(2024, 1, 1))
79
+
80
+ # A sub-album for an algorithm's results, and a DICOMweb write token to upload into it (STOW-RS).
81
+ try:
82
+ results = isengard.albums.create_sub_album(album.album_id, 'Segmentations v2', AlbumCategory.ALGORITHM)
83
+ except ConflictError:
84
+ results = next(a for a in isengard.albums.iter(project=album.project_id) if a.name == 'Segmentations v2')
85
+ token = isengard.album_tokens.create(results.album_id, 'pipeline', dt.timedelta(days=7), can_write=True)
86
+ print(token.token) # the raw value is only returned once
87
+
88
+ # … once the work is done, the application revokes its album token:
89
+ isengard.album_tokens.revoke_self(token.token)
90
+ ```
91
+
92
+ ### Reference
93
+
94
+ | Method | Call |
95
+ |---|---|
96
+ | `isengard.me()` | `GET /me/` |
97
+ | `projects.list(limit, offset)` / `projects.iter(page_size)` | `GET /projects/` |
98
+ | `projects.get(project_id)` | `GET /projects/{project_id}/` |
99
+ | `projects.create_album(project_id, name, category, …)` | `POST /projects/{project_id}/albums/` |
100
+ | `albums.list(project, permissions, keyword, …)` / `albums.iter(…)` | `GET /albums/` |
101
+ | `albums.get(album_id)` | `GET /albums/{album_id}/` |
102
+ | `albums.update(album_id, name=…, keywords=…, …)` | `PATCH /albums/{album_id}/` |
103
+ | `albums.studies(album_id, …)` / `albums.iter_studies(…)` | `GET /albums/{album_id}/studies/` |
104
+ | `albums.series(album_id, modality)` / `albums.iter_series(…)` | `GET /albums/{album_id}/series/` |
105
+ | `albums.study_series(album_id, study_uid, own)` | `GET /albums/{album_id}/studies/{study_uid}/series/` |
106
+ | `albums.create_sub_album(album_id, name, category)` | `POST /albums/{album_id}/sub-albums/` |
107
+ | `albums.copy_series(album_id, destination, series)` | `POST /albums/{album_id}/copy/` |
108
+ | `albums.duplicate(album_id, name, mode, category, parent_names)` | `POST /albums/{album_id}/duplicate/` |
109
+ | `album_tokens.list(album_id, inactive)` / `album_tokens.iter(…)` | `GET /albums/{album_id}/tokens/` |
110
+ | `album_tokens.create(album_id, description, expiration, can_read, can_write)` | `POST /albums/{album_id}/tokens/` |
111
+ | `album_tokens.revoke(album_id, token_id)` | `DELETE /albums/{album_id}/tokens/{token_id}/` |
112
+ | `album_tokens.revoke_self(album_token)` | `DELETE /album-tokens/self/` |
113
+ | `members.list(album_id)` | `GET /albums/{album_id}/members/` |
114
+ | `members.add(album_id, user, permissions)` | `POST /albums/{album_id}/members/` |
115
+ | `members.update(album_id, user_id, grant, revoke)` | `PATCH /albums/{album_id}/members/{user_id}/` |
116
+ | `members.remove(album_id, user_id)` | `DELETE /albums/{album_id}/members/{user_id}/` |
117
+
118
+ Responses are pydantic models (`Album`, `Series`, `AlbumStudy`, …); unknown fields from a newer Isengard version are
119
+ preserved. The documentation of each call (required permissions, error cases) is in the docstrings, and in Isengard's
120
+ OpenAPI (`/api/v1/docs/`).
121
+
122
+ ### Errors
123
+
124
+ An API error raises a subclass of `pysengard.APIError`, with `status_code` and `detail`:
125
+
126
+ | Status | Exception |
127
+ |---|---|
128
+ | 401 | `AuthenticationError` (token missing, unknown, expired or revoked) |
129
+ | 403 | `PermissionDeniedError` (album visible, but permission or scope missing) |
130
+ | 404 | `NotFoundError` (nonexistent or not visible) |
131
+ | 409 | `ConflictError` (name already taken in the project, member already present, …) |
132
+ | 422 | `UnprocessableEntityError` (request rejected or invalid) |
133
+ | 429 | `RateLimitError` (after `max_retries` retries) |
134
+ | 5xx | `ServerError` |
135
+
136
+ An unreachable server raises `IsengardConnectionError`. All of them inherit from `IsengardError`.
137
+
138
+ ## License
139
+
140
+ [MIT](LICENSE)
@@ -0,0 +1,125 @@
1
+ # pysengard
2
+
3
+ Python client for the **Isengard REST API v1** (`/api/v1/`): projects, albums and sub-albums, studies and series, album
4
+ copy and duplication, album DICOMweb tokens and album members.
5
+
6
+ The DICOMweb API (`/api/dicomweb/`: QIDO-RS, WADO-RS, STOW-RS) is not covered: use a DICOMweb client (for example
7
+ [dicomweb-client](https://github.com/ImagingDataCommons/dicomweb-client)) with an album token created by `pysengard`.
8
+
9
+ ## Installation
10
+
11
+ Python 3.10 or newer.
12
+
13
+ ```bash
14
+ pip install pysengard
15
+ # or, in a uv project
16
+ uv add pysengard
17
+ ```
18
+
19
+ ## Authentication
20
+
21
+ Every call requires a **personal token**, created on Isengard's *Profile → Tokens* page (or the access token of an
22
+ application that signs its users in with Isengard via OpenID Connect, limited by its scopes).
23
+
24
+ ```python
25
+ from pysengard import Isengard
26
+
27
+ isengard = Isengard('https://isengard.example.org', token='…')
28
+ ```
29
+
30
+ Without arguments, the client reads the `ISENGARD_URL` and `ISENGARD_TOKEN` environment variables:
31
+
32
+ ```python
33
+ isengard = Isengard() # or Isengard.from_env()
34
+ print(isengard.me().username)
35
+ ```
36
+
37
+ The URL can be either the site's or the API's (`…/api/v1`). Options: `timeout`, `verify` (TLS certificate), `max_retries`
38
+ (retries of a request rejected with 429 by the rate limit), `headers`, `transport` (httpx).
39
+
40
+ ## Usage
41
+
42
+ ```python
43
+ import datetime as dt
44
+
45
+ from pysengard import AlbumCategory, ConflictError, Isengard, Permission
46
+
47
+ with Isengard() as isengard:
48
+ # Visible projects and albums: list() returns one page, iter() walks through all pages.
49
+ page = isengard.projects.list(limit=20)
50
+ print(page.count, [project.name for project in page])
51
+
52
+ for album in isengard.albums.iter(permissions=[Permission.CAN_CREATE_TOKEN]):
53
+ print(album.album_id, album.name, album.series_count)
54
+
55
+ album = isengard.albums.get('6DgJD3F7')
56
+
57
+ # Studies and series of an album, with the filters of its page.
58
+ for study in isengard.albums.iter_studies(album.album_id, patient_name='john doe', modalities=['CT', 'MR']):
59
+ for series in isengard.albums.study_series(album.album_id, study.uid):
60
+ print(study.patient_id, series.modality, series.uid)
61
+
62
+ # Search across all visible albums (not paginated: has_more suggests narrowing the query).
63
+ result = isengard.studies.search('doe', date_from=dt.date(2024, 1, 1))
64
+
65
+ # A sub-album for an algorithm's results, and a DICOMweb write token to upload into it (STOW-RS).
66
+ try:
67
+ results = isengard.albums.create_sub_album(album.album_id, 'Segmentations v2', AlbumCategory.ALGORITHM)
68
+ except ConflictError:
69
+ results = next(a for a in isengard.albums.iter(project=album.project_id) if a.name == 'Segmentations v2')
70
+ token = isengard.album_tokens.create(results.album_id, 'pipeline', dt.timedelta(days=7), can_write=True)
71
+ print(token.token) # the raw value is only returned once
72
+
73
+ # … once the work is done, the application revokes its album token:
74
+ isengard.album_tokens.revoke_self(token.token)
75
+ ```
76
+
77
+ ### Reference
78
+
79
+ | Method | Call |
80
+ |---|---|
81
+ | `isengard.me()` | `GET /me/` |
82
+ | `projects.list(limit, offset)` / `projects.iter(page_size)` | `GET /projects/` |
83
+ | `projects.get(project_id)` | `GET /projects/{project_id}/` |
84
+ | `projects.create_album(project_id, name, category, …)` | `POST /projects/{project_id}/albums/` |
85
+ | `albums.list(project, permissions, keyword, …)` / `albums.iter(…)` | `GET /albums/` |
86
+ | `albums.get(album_id)` | `GET /albums/{album_id}/` |
87
+ | `albums.update(album_id, name=…, keywords=…, …)` | `PATCH /albums/{album_id}/` |
88
+ | `albums.studies(album_id, …)` / `albums.iter_studies(…)` | `GET /albums/{album_id}/studies/` |
89
+ | `albums.series(album_id, modality)` / `albums.iter_series(…)` | `GET /albums/{album_id}/series/` |
90
+ | `albums.study_series(album_id, study_uid, own)` | `GET /albums/{album_id}/studies/{study_uid}/series/` |
91
+ | `albums.create_sub_album(album_id, name, category)` | `POST /albums/{album_id}/sub-albums/` |
92
+ | `albums.copy_series(album_id, destination, series)` | `POST /albums/{album_id}/copy/` |
93
+ | `albums.duplicate(album_id, name, mode, category, parent_names)` | `POST /albums/{album_id}/duplicate/` |
94
+ | `album_tokens.list(album_id, inactive)` / `album_tokens.iter(…)` | `GET /albums/{album_id}/tokens/` |
95
+ | `album_tokens.create(album_id, description, expiration, can_read, can_write)` | `POST /albums/{album_id}/tokens/` |
96
+ | `album_tokens.revoke(album_id, token_id)` | `DELETE /albums/{album_id}/tokens/{token_id}/` |
97
+ | `album_tokens.revoke_self(album_token)` | `DELETE /album-tokens/self/` |
98
+ | `members.list(album_id)` | `GET /albums/{album_id}/members/` |
99
+ | `members.add(album_id, user, permissions)` | `POST /albums/{album_id}/members/` |
100
+ | `members.update(album_id, user_id, grant, revoke)` | `PATCH /albums/{album_id}/members/{user_id}/` |
101
+ | `members.remove(album_id, user_id)` | `DELETE /albums/{album_id}/members/{user_id}/` |
102
+
103
+ Responses are pydantic models (`Album`, `Series`, `AlbumStudy`, …); unknown fields from a newer Isengard version are
104
+ preserved. The documentation of each call (required permissions, error cases) is in the docstrings, and in Isengard's
105
+ OpenAPI (`/api/v1/docs/`).
106
+
107
+ ### Errors
108
+
109
+ An API error raises a subclass of `pysengard.APIError`, with `status_code` and `detail`:
110
+
111
+ | Status | Exception |
112
+ |---|---|
113
+ | 401 | `AuthenticationError` (token missing, unknown, expired or revoked) |
114
+ | 403 | `PermissionDeniedError` (album visible, but permission or scope missing) |
115
+ | 404 | `NotFoundError` (nonexistent or not visible) |
116
+ | 409 | `ConflictError` (name already taken in the project, member already present, …) |
117
+ | 422 | `UnprocessableEntityError` (request rejected or invalid) |
118
+ | 429 | `RateLimitError` (after `max_retries` retries) |
119
+ | 5xx | `ServerError` |
120
+
121
+ An unreachable server raises `IsengardConnectionError`. All of them inherit from `IsengardError`.
122
+
123
+ ## License
124
+
125
+ [MIT](LICENSE)
@@ -0,0 +1,54 @@
1
+ [project]
2
+ name = "pysengard"
3
+ dynamic = ["version"]
4
+ description = "Python client for the Isengard REST API (v1)"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.10"
9
+ authors = [{ name = "Yannick Lemaréchal" }]
10
+ dependencies = [
11
+ "httpx>=0.27",
12
+ "pydantic>=2.6",
13
+ ]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Scientific/Engineering :: Medical Science Apps.",
17
+ "Typing :: Typed",
18
+ ]
19
+
20
+ [dependency-groups]
21
+ dev = [
22
+ "pytest>=8",
23
+ "respx>=0.21",
24
+ "ruff>=0.6",
25
+ ]
26
+
27
+ [build-system]
28
+ requires = ["hatchling>=1.27"]
29
+ build-backend = "hatchling.build"
30
+
31
+ [tool.hatch.version]
32
+ path = "src/pysengard/_version.py"
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["src/pysengard"]
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
39
+
40
+ [tool.ruff]
41
+ line-length = 140
42
+ target-version = "py310"
43
+
44
+ [tool.ruff.lint]
45
+ select = ["E", "W", "F", "I", "B", "S", "UP", "SIM"]
46
+
47
+ [tool.ruff.lint.per-file-ignores]
48
+ "tests/*" = ["S101", "S105", "S106"]
49
+
50
+ [tool.ruff.lint.isort]
51
+ combine-as-imports = true
52
+
53
+ [tool.ruff.format]
54
+ quote-style = "single"
@@ -0,0 +1,75 @@
1
+ """pysengard — a Python client for the Isengard REST API v1."""
2
+
3
+ from ._version import __version__
4
+ from .client import Isengard
5
+ from .exceptions import (
6
+ APIError,
7
+ AuthenticationError,
8
+ BadRequestError,
9
+ ConflictError,
10
+ IsengardConnectionError,
11
+ IsengardError,
12
+ NotFoundError,
13
+ PermissionDeniedError,
14
+ RateLimitError,
15
+ ServerError,
16
+ UnprocessableEntityError,
17
+ )
18
+ from .models import (
19
+ Album,
20
+ AlbumCategory,
21
+ AlbumDuplication,
22
+ AlbumStudy,
23
+ AlbumToken,
24
+ CreatedAlbumToken,
25
+ DuplicationMode,
26
+ Me,
27
+ Member,
28
+ Page,
29
+ Permission,
30
+ Project,
31
+ ProjectAlbum,
32
+ Series,
33
+ SeriesCopyResult,
34
+ StudyAlbum,
35
+ StudyHit,
36
+ StudySearchResult,
37
+ TokenInfo,
38
+ User,
39
+ )
40
+
41
+ __all__ = [
42
+ 'APIError',
43
+ 'Album',
44
+ 'AlbumCategory',
45
+ 'AlbumDuplication',
46
+ 'AlbumStudy',
47
+ 'AlbumToken',
48
+ 'AuthenticationError',
49
+ 'BadRequestError',
50
+ 'ConflictError',
51
+ 'CreatedAlbumToken',
52
+ 'DuplicationMode',
53
+ 'Isengard',
54
+ 'IsengardConnectionError',
55
+ 'IsengardError',
56
+ 'Me',
57
+ 'Member',
58
+ 'NotFoundError',
59
+ 'Page',
60
+ 'Permission',
61
+ 'PermissionDeniedError',
62
+ 'Project',
63
+ 'ProjectAlbum',
64
+ 'RateLimitError',
65
+ 'Series',
66
+ 'SeriesCopyResult',
67
+ 'ServerError',
68
+ 'StudyAlbum',
69
+ 'StudyHit',
70
+ 'StudySearchResult',
71
+ 'TokenInfo',
72
+ 'UnprocessableEntityError',
73
+ 'User',
74
+ '__version__',
75
+ ]
@@ -0,0 +1,64 @@
1
+ """Encoding of the paths, query parameters and JSON bodies of the requests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ from collections.abc import Mapping
7
+ from enum import Enum
8
+ from typing import Any
9
+ from urllib.parse import quote
10
+
11
+ API_PREFIX = '/api/v1'
12
+
13
+
14
+ def api_root(base_url: str) -> str:
15
+ """``https://isengard.example`` (or ``…/api/v1``) → ``https://isengard.example/api/v1/``."""
16
+ root = base_url.rstrip('/')
17
+ if not root.endswith(API_PREFIX):
18
+ root += API_PREFIX
19
+ return root + '/'
20
+
21
+
22
+ def path(*segments: Any) -> str:
23
+ """The relative path of an endpoint, its segments quoted, with the trailing slash the API expects."""
24
+ return '/'.join(quote(str(segment), safe='') for segment in segments) + '/'
25
+
26
+
27
+ def jsonable(value: Any) -> Any:
28
+ """Enums by their value, dates in ISO 8601, recursively."""
29
+ if isinstance(value, Enum):
30
+ return value.value
31
+ if isinstance(value, dt.datetime):
32
+ # A naive datetime is a local time: send its offset, so that the server does not read it in its own time zone.
33
+ return (value if value.tzinfo else value.astimezone()).isoformat()
34
+ if isinstance(value, dt.date):
35
+ return value.isoformat()
36
+ if isinstance(value, Mapping):
37
+ return {str(key): jsonable(item) for key, item in value.items()}
38
+ if isinstance(value, (list, tuple, set, frozenset)):
39
+ return [jsonable(item) for item in value]
40
+ return value
41
+
42
+
43
+ def body(**fields: Any) -> dict[str, Any]:
44
+ """A JSON body without the fields left to ``None`` (not sent: the API keeps or defaults them)."""
45
+ return {key: jsonable(value) for key, value in fields.items() if value is not None}
46
+
47
+
48
+ def _query_value(value: Any) -> Any:
49
+ if isinstance(value, bool):
50
+ return 'true' if value else 'false'
51
+ return jsonable(value)
52
+
53
+
54
+ def query(params: Mapping[str, Any]) -> list[tuple[str, Any]]:
55
+ """Query parameters without the ``None`` ones, lists repeated (``?modality=CT&modality=MR``)."""
56
+ pairs: list[tuple[str, Any]] = []
57
+ for key, value in params.items():
58
+ if value is None:
59
+ continue
60
+ if isinstance(value, (list, tuple, set, frozenset)):
61
+ pairs.extend((key, _query_value(item)) for item in value)
62
+ else:
63
+ pairs.append((key, _query_value(value)))
64
+ return pairs
@@ -0,0 +1 @@
1
+ __version__ = '0.1.0'