python-re3data-v2 0.1.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.
- python_re3data_v2-0.1.0.dist-info/METADATA +215 -0
- python_re3data_v2-0.1.0.dist-info/RECORD +19 -0
- python_re3data_v2-0.1.0.dist-info/WHEEL +4 -0
- python_re3data_v2-0.1.0.dist-info/entry_points.txt +2 -0
- python_re3data_v2-0.1.0.dist-info/licenses/LICENSE +21 -0
- re3data/__init__.py +31 -0
- re3data/__main__.py +6 -0
- re3data/_cli.py +114 -0
- re3data/_client/__init__.py +14 -0
- re3data/_client/_async.py +143 -0
- re3data/_client/_sync.py +145 -0
- re3data/_client/base.py +152 -0
- re3data/_exceptions.py +9 -0
- re3data/_parser.py +443 -0
- re3data/_resources/__init__.py +19 -0
- re3data/_resources/repository.py +564 -0
- re3data/_resources/repository_list.py +66 -0
- re3data/_response.py +34 -0
- re3data/_serializer.py +82 -0
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: python-re3data-v2
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The Pythonic client for the re3data API (v40, schema 4.0).
|
|
5
|
+
Project-URL: Changelog, https://github.com/AstrayChao/python-re3data-v2/blob/master/CHANGELOG.md
|
|
6
|
+
Project-URL: Repository, https://github.com/AstrayChao/python-re3data-v2
|
|
7
|
+
Project-URL: Issues, https://github.com/AstrayChao/python-re3data-v2/issues
|
|
8
|
+
Author: data-sync maintainers
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: api,api-client,metadata,re3data,repositories,research data
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
18
|
+
Classifier: Topic :: Text Processing :: Markup :: XML
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.14
|
|
21
|
+
Requires-Dist: httpx>=0.28
|
|
22
|
+
Provides-Extra: all
|
|
23
|
+
Requires-Dist: typer>=0.16; extra == 'all'
|
|
24
|
+
Provides-Extra: cli
|
|
25
|
+
Requires-Dist: typer>=0.16; extra == 'cli'
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
<div align="center">
|
|
29
|
+
|
|
30
|
+
# python-re3data-v2
|
|
31
|
+
|
|
32
|
+
**The Pythonic client for the [re3data](https://www.re3data.org) API — v40 · schema 4.0 · Python 3.14+**
|
|
33
|
+
|
|
34
|
+
[](https://pypi.org/project/python-re3data-v2/)
|
|
35
|
+
[](pyproject.toml)
|
|
36
|
+
[](https://github.com/AstrayChao/python-re3data-v2/actions/workflows/test.yml)
|
|
37
|
+
[](LICENSE)
|
|
38
|
+
[](https://docs.astral.sh/ruff/)
|
|
39
|
+
[](https://github.com/afuetterer/python-re3data)
|
|
40
|
+
|
|
41
|
+
[English](README.md) · [简体中文](README.zh-CN.md)
|
|
42
|
+
|
|
43
|
+
</div>
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
> [!NOTE]
|
|
48
|
+
> **Why this fork exists** — the original client [`python-re3data`](https://github.com/afuetterer/python-re3data)
|
|
49
|
+
> by Heinz-Alexander Fütterer (MIT) has been **archived** and targets the deprecated
|
|
50
|
+
> `/api/beta` endpoints (schema 2-2). This repository is an independent re-implementation,
|
|
51
|
+
> built from scratch against the current **v40 REST API** and the
|
|
52
|
+
> [re3data metadata schema 4.0](https://doi.org/10.48440/re3.014), keeping the familiar
|
|
53
|
+
> architecture and dict conventions of the original.
|
|
54
|
+
|
|
55
|
+
> [!WARNING]
|
|
56
|
+
> **Not production-ready yet.** This library is young: the v40 API and schema 4.0 are new,
|
|
57
|
+
> and edge cases may still exist. **Use with caution in production environments until the
|
|
58
|
+
> first stable release.** 非正式发布阶段,请谨慎用于生产环境。
|
|
59
|
+
|
|
60
|
+
## ✨ Highlights
|
|
61
|
+
|
|
62
|
+
| | |
|
|
63
|
+
|---|---|
|
|
64
|
+
| 🚀 **v40 endpoints** | `GET /api/v40/repositories` · `GET /api/v40/repository/{id}` |
|
|
65
|
+
| 🧬 **Typed schema 4.0 models** | Hand-written dataclasses mirroring the [official XSD](https://schema.re3data.org/4-0/re3dataV4-0.xsd) — no `xsdata` |
|
|
66
|
+
| 🛡️ **Drift-tolerant parsing** | Unknown vocabulary values / malformed dates never break a parse |
|
|
67
|
+
| ⚡ **Sync + async** | `Client` and `AsyncClient` on top of `httpx` |
|
|
68
|
+
| 🔄 **Flexible serialization** | `dataclass` · `dict` · `json` · `xml` · `csv` · `response` |
|
|
69
|
+
| 🎛️ **Facet filters** | ~30 v40 filter facets via a single `filters` mapping |
|
|
70
|
+
| 🪶 **Minimal footprint** | Python 3.14+, the only runtime dependency is `httpx` |
|
|
71
|
+
|
|
72
|
+
## 📦 Installation
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pip install python-re3data-v2 # or: uv add python-re3data-v2
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
With the optional CLI:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
pip install 'python-re3data-v2[cli]'
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## 🚀 Quick start
|
|
85
|
+
|
|
86
|
+
### Module-level manager (synchronous)
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
import re3data
|
|
90
|
+
|
|
91
|
+
summaries = re3data.repositories.list(query="UCL")
|
|
92
|
+
for summary in summaries:
|
|
93
|
+
print(summary.id, summary.doi, summary.name, summary.href)
|
|
94
|
+
|
|
95
|
+
repository = re3data.repositories.get("r3d100012417")
|
|
96
|
+
print(repository.repositoryName.value) # "UCL Discovery"
|
|
97
|
+
print(repository.identifiers.doi) # "https://doi.org/10.17616/R34F41"
|
|
98
|
+
print(repository.subject[0].subjectId) # "4" (DFG classification id)
|
|
99
|
+
print(repository.entryDate) # datetime.date(2017, 7, 21)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Explicit clients
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from re3data import Client, AsyncClient
|
|
106
|
+
|
|
107
|
+
client = Client()
|
|
108
|
+
repository = client.repositories.get("r3d100012417")
|
|
109
|
+
|
|
110
|
+
async with AsyncClient() as async_client:
|
|
111
|
+
repository = await async_client.repositories.get("r3d100012417")
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Return types
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
from re3data import Client, ReturnType
|
|
118
|
+
|
|
119
|
+
client = Client()
|
|
120
|
+
payload = client.repositories.get("r3d100012417", return_type=ReturnType.DICT)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`ReturnType.DICT` reproduces the document with XML-style keys (`repositoryUrl`,
|
|
124
|
+
`identifiers.re3data`, `subject[].subjectId`, …), localized elements as
|
|
125
|
+
`{"value": ..., "language": ...}` and dates as ISO-8601 strings — the same
|
|
126
|
+
conventions the original `python-re3data` established, so existing consumers
|
|
127
|
+
keep working with minimal changes.
|
|
128
|
+
|
|
129
|
+
### Facet filters
|
|
130
|
+
|
|
131
|
+
The v40 list endpoint supports ~30 facet filters, serialized as repeated
|
|
132
|
+
`name[]` query parameters:
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
client.repositories.list(
|
|
136
|
+
query="climate",
|
|
137
|
+
filters={"countries": ["DEU", "NZL"], "certificates": "CoreTrustSeal"},
|
|
138
|
+
)
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### CLI
|
|
142
|
+
|
|
143
|
+
```console
|
|
144
|
+
$ re3data repository get r3d100012417 --return-type json
|
|
145
|
+
$ re3data repository list --query "UCL" --return-type csv
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## 🔀 Differences vs. the original `python-re3data`
|
|
149
|
+
|
|
150
|
+
| Aspect | python-re3data 0.10 | python-re3data-v2 |
|
|
151
|
+
|---|---|---|
|
|
152
|
+
| API | `/api/beta` (deprecated) | `/api/v40` (current) |
|
|
153
|
+
| Metadata schema | 2-2 | **4.0** (August 2023) |
|
|
154
|
+
| Python | ≥ 3.10 | **≥ 3.14** |
|
|
155
|
+
| XML binding | `xsdata` codegen | stdlib `ElementTree` + hand-written models |
|
|
156
|
+
| List entry fields | id, doi, link | id, doi, **name**, link |
|
|
157
|
+
| `dataframe` return type | ✅ (requires pandas) | ❌ (dropped; `csv` is built-in) |
|
|
158
|
+
| Facet filters | `query` only | `query` + `filters` mapping |
|
|
159
|
+
|
|
160
|
+
A complete field-by-field mapping between schema 2-2 and 4.0 is available in
|
|
161
|
+
[docs/schema-mapping.md](docs/schema-mapping.md); the underlying research and
|
|
162
|
+
migration notes live in [docs/research.md](docs/research.md).
|
|
163
|
+
|
|
164
|
+
## ⚠️ Known upstream issues
|
|
165
|
+
|
|
166
|
+
- `GET /api/v40/repositories` **without** a `query`/filter currently fails with
|
|
167
|
+
HTTP 500 server-side (the deprecated beta endpoint behaves the same). Listing
|
|
168
|
+
everything therefore requires a query or filter for now; the client surfaces
|
|
169
|
+
the error transparently.
|
|
170
|
+
- The API only serves `application/xml` — there is no JSON representation.
|
|
171
|
+
- Live data occasionally deviates from the XSD vocabularies (e.g.
|
|
172
|
+
`"institutional membership"` vs. `"institutionalMembership"`). Vocabulary
|
|
173
|
+
fields are typed as plain `str` and parsed verbatim, so unknown values never
|
|
174
|
+
raise.
|
|
175
|
+
|
|
176
|
+
## 📚 API reference
|
|
177
|
+
|
|
178
|
+
`re3data.repositories` · `re3data.Client` · `re3data.AsyncClient`
|
|
179
|
+
|
|
180
|
+
| Method | Description |
|
|
181
|
+
|---|---|
|
|
182
|
+
| `repositories.list(query=None, filters=None, return_type=..., count=False)` | List repositories, optionally filtered |
|
|
183
|
+
| `repositories.get(repository_id, return_type=...)` | Fetch one repository by its re3data id |
|
|
184
|
+
|
|
185
|
+
<details>
|
|
186
|
+
<summary>Reference enums exported for convenience</summary>
|
|
187
|
+
|
|
188
|
+
`RepositoryType`, `ProviderType`, `DatabaseAccessType`, `DatabaseAccessRestriction`,
|
|
189
|
+
`DataAccessType`, `DataAccessRestriction`, `DataUploadType`, `DataUploadRestriction`,
|
|
190
|
+
`InstitutionType`, `ResponsibilityType`, `RelatedRepositoryType`, `YesNo`
|
|
191
|
+
|
|
192
|
+
</details>
|
|
193
|
+
|
|
194
|
+
## 🛠️ Development
|
|
195
|
+
|
|
196
|
+
```bash
|
|
197
|
+
uv sync --all-groups # Python 3.14 environment
|
|
198
|
+
uv run pytest # unit + integration (offline, real v40 XML fixtures)
|
|
199
|
+
uv run pytest -m e2e # live API smoke tests
|
|
200
|
+
uv run ruff check . # lint
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
## 📄 License
|
|
204
|
+
|
|
205
|
+
[MIT](LICENSE) — same as the original project. The architecture and dict
|
|
206
|
+
conventions are deliberately compatible with
|
|
207
|
+
[python-re3data](https://github.com/afuetterer/python-re3data) by
|
|
208
|
+
Heinz-Alexander Fütterer; this repository shares no code with it.
|
|
209
|
+
|
|
210
|
+
## 🙏 Credits
|
|
211
|
+
|
|
212
|
+
- [python-re3data](https://github.com/afuetterer/python-re3data) — the original
|
|
213
|
+
Pythonic client this project continues, in spirit and API shape.
|
|
214
|
+
- [re3data.org](https://www.re3data.org) — registry of research data
|
|
215
|
+
repositories, Karlsruhe Institute of Technology / FIZ Karlsruhe.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
re3data/__init__.py,sha256=mjaOvHQacouNp1kSaVmO02laplIZufDJIMlIX_QmT0w,865
|
|
2
|
+
re3data/__main__.py,sha256=EQ5SBDg5guM7tneBKSCyEQHlHO4qwZ3kUQ_zur4E5OQ,116
|
|
3
|
+
re3data/_cli.py,sha256=QGLWrwuQMO-JpN-UbOokiML2b81FVsWR2gybIeYOyD0,3371
|
|
4
|
+
re3data/_exceptions.py,sha256=bfIiXGRChBXPuFbb4IBGjm448Abh0JpGXdhyGPUR-Cc,284
|
|
5
|
+
re3data/_parser.py,sha256=McW3T9-3cNx_DwtxAZCO-4ZAfV_Ay53-W3EEH6qm7jI,17796
|
|
6
|
+
re3data/_response.py,sha256=NfJxNp02RStGD5Y9Zwi6xTB3LZSpVH8JPcshJqdnx3I,942
|
|
7
|
+
re3data/_serializer.py,sha256=fL0P_JUf9c6KiL7xES94K_96L11WjBWwTzdhM3B2o-0,2758
|
|
8
|
+
re3data/_client/__init__.py,sha256=NMKXqeaP8dw20XHVakHq1Bgtx3Ew0K_FovPIK_VGVII,362
|
|
9
|
+
re3data/_client/_async.py,sha256=JyBIkWwrFB93Et44NUf_tebvlVohhJTPN7ncQbeMZ8Q,5695
|
|
10
|
+
re3data/_client/_sync.py,sha256=RahdqhYhI2u6bdpqnY3URZccVCm7vPEsP42buVs15UQ,5639
|
|
11
|
+
re3data/_client/base.py,sha256=H7nUuGHwyCpzehpXF8RbLOpwklak19nl_hMjqPBWf8I,5288
|
|
12
|
+
re3data/_resources/__init__.py,sha256=UfXmXRBbD1RzjGcnW0xp3rfyXZNaR0KeRT7n2Cx4Q6Y,351
|
|
13
|
+
re3data/_resources/repository.py,sha256=dwVZvcE-qAxJLQl9rMCGEuo3f5bDjyqdfa5Upus8X28,18726
|
|
14
|
+
re3data/_resources/repository_list.py,sha256=umH1QBcSiG1k_ZWS0V3vm7MP_kzw7wW9wpsHEHhtuB8,1753
|
|
15
|
+
python_re3data_v2-0.1.0.dist-info/METADATA,sha256=FlygnealhMKCpydQLSVN5ycxRpM5fjE3B4nPH3KvALY,8455
|
|
16
|
+
python_re3data_v2-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
17
|
+
python_re3data_v2-0.1.0.dist-info/entry_points.txt,sha256=P8OdB3PXzCCxLRMk7Seom7t36rHOk6erUlaaik3SHNo,49
|
|
18
|
+
python_re3data_v2-0.1.0.dist-info/licenses/LICENSE,sha256=r4wQ3b_41L-VoaX1Hgy2FeSPtcmiuu0MPhZyO9NzaEk,1078
|
|
19
|
+
python_re3data_v2-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 data-sync maintainers
|
|
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.
|
re3data/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""python-re3data-v2: the Pythonic client for the re3data API (v40, schema 4.0)."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__: str = version("python-re3data-v2")
|
|
7
|
+
except PackageNotFoundError: # pragma: no cover - package not installed
|
|
8
|
+
__version__ = "0.0.0"
|
|
9
|
+
|
|
10
|
+
from re3data._client import AsyncClient, Client, ReturnType
|
|
11
|
+
from re3data._exceptions import Re3dataError, RepositoryNotFoundError
|
|
12
|
+
from re3data._resources import Link, Re3Data, Repository, RepositoryList, RepositorySummary
|
|
13
|
+
from re3data._response import Response
|
|
14
|
+
|
|
15
|
+
__all__ = (
|
|
16
|
+
"AsyncClient",
|
|
17
|
+
"Client",
|
|
18
|
+
"Link",
|
|
19
|
+
"Re3Data",
|
|
20
|
+
"Re3dataError",
|
|
21
|
+
"Repository",
|
|
22
|
+
"RepositoryList",
|
|
23
|
+
"RepositoryNotFoundError",
|
|
24
|
+
"RepositorySummary",
|
|
25
|
+
"Response",
|
|
26
|
+
"ReturnType",
|
|
27
|
+
"__version__",
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
_client = Client()
|
|
31
|
+
repositories = _client.repositories
|
re3data/__main__.py
ADDED
re3data/_cli.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""python-re3data-v2 command line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Annotated
|
|
9
|
+
|
|
10
|
+
from rich.console import Console
|
|
11
|
+
|
|
12
|
+
import re3data
|
|
13
|
+
from re3data._client import ReturnType
|
|
14
|
+
from re3data._exceptions import RepositoryNotFoundError
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
import typer
|
|
20
|
+
except ImportError: # pragma: no cover - depends on optional extra
|
|
21
|
+
logger.error("`typer` is missing. Please run 'pip install python-re3data-v2[cli]' to use the CLI.")
|
|
22
|
+
sys.exit(1)
|
|
23
|
+
|
|
24
|
+
console = Console()
|
|
25
|
+
|
|
26
|
+
CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
|
|
27
|
+
|
|
28
|
+
app = typer.Typer(no_args_is_help=True, context_settings=CONTEXT_SETTINGS)
|
|
29
|
+
repositories_app = typer.Typer(no_args_is_help=True)
|
|
30
|
+
app.add_typer(repositories_app, name="repository")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _version_callback(show_version: bool) -> None:
|
|
34
|
+
# Ref: https://typer.tiangolo.com/tutorial/options/version/
|
|
35
|
+
if show_version:
|
|
36
|
+
console.print(re3data.__version__)
|
|
37
|
+
raise typer.Exit(code=0)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _write_to_file(response: object, outfile: Path | None) -> None:
|
|
41
|
+
"""Write the given response to the specified file, asking before overwriting."""
|
|
42
|
+
if outfile and outfile.exists():
|
|
43
|
+
overwrite = typer.confirm(f"{outfile} already exists. Do you want to overwrite it?")
|
|
44
|
+
if not overwrite:
|
|
45
|
+
return
|
|
46
|
+
if outfile:
|
|
47
|
+
outfile.write_text(str(response), encoding="utf-8")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@app.callback(context_settings=CONTEXT_SETTINGS)
|
|
51
|
+
def callback(
|
|
52
|
+
version: Annotated[
|
|
53
|
+
bool,
|
|
54
|
+
typer.Option(
|
|
55
|
+
"--version",
|
|
56
|
+
"-V",
|
|
57
|
+
help="Show python-re3data-v2 version and exit.",
|
|
58
|
+
callback=_version_callback,
|
|
59
|
+
is_eager=True,
|
|
60
|
+
),
|
|
61
|
+
] = False,
|
|
62
|
+
) -> None:
|
|
63
|
+
"""python-re3data-v2: the Pythonic client for the re3data API (v40, schema 4.0)."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@repositories_app.command("list")
|
|
67
|
+
def list_repositories(
|
|
68
|
+
query: Annotated[
|
|
69
|
+
str | None,
|
|
70
|
+
typer.Option(
|
|
71
|
+
help="A query to filter the results. If provided, only repositories matching the query will be returned."
|
|
72
|
+
),
|
|
73
|
+
] = None,
|
|
74
|
+
return_type: ReturnType = ReturnType.DATACLASS,
|
|
75
|
+
count: bool = False,
|
|
76
|
+
outfile: Annotated[
|
|
77
|
+
Path | None,
|
|
78
|
+
typer.Option(
|
|
79
|
+
file_okay=True,
|
|
80
|
+
dir_okay=False,
|
|
81
|
+
writable=True,
|
|
82
|
+
),
|
|
83
|
+
] = None,
|
|
84
|
+
) -> None:
|
|
85
|
+
"""List the metadata of repositories in the re3data API."""
|
|
86
|
+
response = re3data.repositories.list(query, return_type, count)
|
|
87
|
+
_write_to_file(response, outfile)
|
|
88
|
+
console.print(response)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@repositories_app.command("get")
|
|
92
|
+
def get_repository(
|
|
93
|
+
repository_id: Annotated[
|
|
94
|
+
str,
|
|
95
|
+
typer.Argument(help="The identifier of the repository to retrieve, e.g. 'r3d100012417'."),
|
|
96
|
+
],
|
|
97
|
+
return_type: ReturnType = ReturnType.DATACLASS,
|
|
98
|
+
outfile: Annotated[
|
|
99
|
+
Path | None,
|
|
100
|
+
typer.Option(
|
|
101
|
+
file_okay=True,
|
|
102
|
+
dir_okay=False,
|
|
103
|
+
writable=True,
|
|
104
|
+
),
|
|
105
|
+
] = None,
|
|
106
|
+
) -> None:
|
|
107
|
+
"""Get the metadata of a specific repository."""
|
|
108
|
+
try:
|
|
109
|
+
response = re3data.repositories.get(repository_id, return_type)
|
|
110
|
+
except RepositoryNotFoundError as error:
|
|
111
|
+
console.print(str(error), style="bold red")
|
|
112
|
+
raise typer.Exit(code=1) from error
|
|
113
|
+
_write_to_file(response, outfile)
|
|
114
|
+
console.print(response)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Clients for the re3data v40 API."""
|
|
2
|
+
|
|
3
|
+
from re3data._client._async import AsyncClient, AsyncRepositoryManager
|
|
4
|
+
from re3data._client._sync import Client, RepositoryManager
|
|
5
|
+
from re3data._client.base import BASE_URL, ReturnType
|
|
6
|
+
|
|
7
|
+
__all__ = (
|
|
8
|
+
"BASE_URL",
|
|
9
|
+
"AsyncClient",
|
|
10
|
+
"AsyncRepositoryManager",
|
|
11
|
+
"Client",
|
|
12
|
+
"RepositoryManager",
|
|
13
|
+
"ReturnType",
|
|
14
|
+
)
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""The asynchronous client to interact with the re3data v40 API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import TYPE_CHECKING, Self
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from re3data._client.base import (
|
|
11
|
+
BaseClient,
|
|
12
|
+
Endpoint,
|
|
13
|
+
ResourceType,
|
|
14
|
+
ReturnType,
|
|
15
|
+
_dispatch_return_type,
|
|
16
|
+
build_query_params,
|
|
17
|
+
is_valid_return_type,
|
|
18
|
+
)
|
|
19
|
+
from re3data._exceptions import RepositoryNotFoundError
|
|
20
|
+
from re3data._response import Response, _build_response
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from re3data._resources import Repository, RepositorySummary
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
async def log_response(response: httpx.Response) -> None:
|
|
29
|
+
"""Log method, URL and status code of an HTTP response on the debug level."""
|
|
30
|
+
logger.debug("[http] Response: %s %s - Status %s", response.request.method, response.request.url, response.status_code)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AsyncRepositoryManager:
|
|
34
|
+
"""An async manager for interacting with the repositories endpoints."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, client: AsyncClient) -> None:
|
|
37
|
+
self._client = client
|
|
38
|
+
|
|
39
|
+
async def list(
|
|
40
|
+
self,
|
|
41
|
+
query: str | None = None,
|
|
42
|
+
return_type: ReturnType = ReturnType.DATACLASS,
|
|
43
|
+
count: bool = False,
|
|
44
|
+
filters: dict[str, str | list[str] | tuple[str, ...]] | None = None,
|
|
45
|
+
) -> list[RepositorySummary] | Response | list[dict] | str | int:
|
|
46
|
+
"""List the metadata of repositories in the re3data API.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
query: A query string to filter the results. If provided, only
|
|
50
|
+
repositories matching the query will be returned.
|
|
51
|
+
return_type: The desired return type for the API resource.
|
|
52
|
+
Defaults to `ReturnType.DATACLASS`.
|
|
53
|
+
count: Whether to return the total number of matching items
|
|
54
|
+
instead of a list of repositories.
|
|
55
|
+
filters: Optional facet filters for the v40 endpoint, e.g.
|
|
56
|
+
``{"countries": ["DEU", "NZL"], "dataAccess": "open"}``.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
Depending on the `return_type`, this is a list of
|
|
60
|
+
RepositorySummary objects, an HTTP response, a dictionary/JSON/CSV
|
|
61
|
+
representation, the original XML, or the count of repositories.
|
|
62
|
+
|
|
63
|
+
Raises:
|
|
64
|
+
ValueError: If an invalid `return_type` is provided.
|
|
65
|
+
httpx.HTTPStatusError: If the server returned an error status code >= 500.
|
|
66
|
+
"""
|
|
67
|
+
is_valid_return_type(return_type)
|
|
68
|
+
params = build_query_params(query, filters)
|
|
69
|
+
response = await self._client._request(Endpoint.REPOSITORY_LIST.value, params)
|
|
70
|
+
return _dispatch_return_type(response, ResourceType.REPOSITORY_LIST, return_type, count)
|
|
71
|
+
|
|
72
|
+
async def get(self, repository_id: str, return_type: ReturnType = ReturnType.DATACLASS) -> Repository | Response | dict | str:
|
|
73
|
+
"""Get the metadata of a specific repository.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
repository_id: The identifier of the repository to retrieve,
|
|
77
|
+
e.g. "r3d100012417".
|
|
78
|
+
return_type: The desired return type for the API resource.
|
|
79
|
+
Defaults to `ReturnType.DATACLASS`.
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
Depending on the `return_type`, this is a Repository object, an
|
|
83
|
+
HTTP response, a dictionary/JSON/CSV representation or the
|
|
84
|
+
original XML.
|
|
85
|
+
|
|
86
|
+
Raises:
|
|
87
|
+
ValueError: If an invalid `return_type` is provided.
|
|
88
|
+
httpx.HTTPStatusError: If the server returned an error status code >= 500.
|
|
89
|
+
RepositoryNotFoundError: If no repository with the given ID is found.
|
|
90
|
+
"""
|
|
91
|
+
is_valid_return_type(return_type)
|
|
92
|
+
response = await self._client._request(Endpoint.REPOSITORY.value.format(repository_id=repository_id))
|
|
93
|
+
if response.status_code == httpx.codes.NOT_FOUND:
|
|
94
|
+
raise RepositoryNotFoundError(f"No repository with id '{repository_id}' available at {response.url}.")
|
|
95
|
+
return _dispatch_return_type(response, ResourceType.REPOSITORY, return_type)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class AsyncClient(BaseClient):
|
|
99
|
+
"""An async client that interacts with the re3data v40 API.
|
|
100
|
+
|
|
101
|
+
Examples:
|
|
102
|
+
>>> async with AsyncClient() as client:
|
|
103
|
+
... await client.repositories.get("r3d100012417")
|
|
104
|
+
Repository(identifiers=Identifiers(re3data='r3d100012417', doi='https://doi.org/10.17616/R34F41'), ...)
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
_client: httpx.AsyncClient
|
|
108
|
+
|
|
109
|
+
def __init__(self, transport: httpx.AsyncBaseTransport | None = None) -> None:
|
|
110
|
+
"""Initialize the client.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
transport: An optional custom httpx transport, e.g. for testing.
|
|
114
|
+
"""
|
|
115
|
+
super().__init__(httpx.AsyncClient, transport)
|
|
116
|
+
self._client.event_hooks["response"] = [log_response]
|
|
117
|
+
self._repository_manager: AsyncRepositoryManager = AsyncRepositoryManager(self)
|
|
118
|
+
|
|
119
|
+
async def __aenter__(self) -> Self:
|
|
120
|
+
return self
|
|
121
|
+
|
|
122
|
+
async def __aexit__(self, *args: object) -> None:
|
|
123
|
+
await self.aclose()
|
|
124
|
+
|
|
125
|
+
async def aclose(self) -> None:
|
|
126
|
+
"""Close the underlying HTTP client and release connections."""
|
|
127
|
+
await self._client.aclose()
|
|
128
|
+
|
|
129
|
+
async def _request(self, path: str, query_params: list[tuple[str, str]] | None = None) -> Response:
|
|
130
|
+
"""Send an HTTP GET request to the specified API endpoint.
|
|
131
|
+
|
|
132
|
+
Raises:
|
|
133
|
+
httpx.HTTPStatusError: If the server returned an error status code >= 500.
|
|
134
|
+
"""
|
|
135
|
+
http_response = await self._client.get(path, params=query_params)
|
|
136
|
+
if http_response.is_server_error:
|
|
137
|
+
http_response.raise_for_status()
|
|
138
|
+
return _build_response(http_response)
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def repositories(self) -> AsyncRepositoryManager:
|
|
142
|
+
"""The repository manager of this client."""
|
|
143
|
+
return self._repository_manager
|