pdc-api 0.4.1__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.
pdc_api/testing.py ADDED
@@ -0,0 +1,314 @@
1
+ from typing import Any
2
+ from uuid import UUID
3
+
4
+ import responses
5
+
6
+ from pdc_api.client import PageableBundle
7
+
8
+ CREATED_AT = "2026-01-01T00:00:00Z"
9
+ CREATED_BY = "00000000-0000-0000-0000-000000000009"
10
+
11
+
12
+ def changemaker_payload(
13
+ *, id: int = 1, name: str = "Acme", keycloak_org_id: str | UUID | None = None, tax_id: str = "12-3456789"
14
+ ) -> dict[str, Any]:
15
+ return {
16
+ "id": id,
17
+ "taxId": tax_id,
18
+ "name": name,
19
+ "keycloakOrganizationId": keycloak_org_id,
20
+ "createdAt": CREATED_AT,
21
+ "createdBy": CREATED_BY,
22
+ "fields": [],
23
+ "fiscalSponsors": [],
24
+ "permissions": {},
25
+ }
26
+
27
+
28
+ def funder_payload(
29
+ *,
30
+ short_code: str = "acme",
31
+ name: str = "Acme Foundation",
32
+ keycloak_org_id: str | UUID | None = None,
33
+ is_collaborative: bool = False,
34
+ ) -> dict[str, Any]:
35
+ return {
36
+ "shortCode": short_code,
37
+ "name": name,
38
+ "keycloakOrganizationId": keycloak_org_id,
39
+ "isCollaborative": is_collaborative,
40
+ "createdAt": CREATED_AT,
41
+ "createdBy": CREATED_BY,
42
+ "permissions": {},
43
+ }
44
+
45
+
46
+ def data_provider_payload(
47
+ *, short_code: str = "pdw", name: str = "Philanthropy Data Warehouse", keycloak_org_id: str | UUID | None = None
48
+ ) -> dict[str, Any]:
49
+ return {
50
+ "shortCode": short_code,
51
+ "name": name,
52
+ "keycloakOrganizationId": keycloak_org_id,
53
+ "createdAt": CREATED_AT,
54
+ "createdBy": CREATED_BY,
55
+ }
56
+
57
+
58
+ def base_field_payload(
59
+ short_code: str = "field", *, data_type: str = "string", category: str = "uncategorized"
60
+ ) -> dict[str, Any]:
61
+ return {
62
+ "shortCode": short_code,
63
+ "label": short_code,
64
+ "category": category,
65
+ "dataType": data_type,
66
+ "description": "",
67
+ "localizations": {},
68
+ "valueRelevanceHours": None,
69
+ "sensitivityClassification": "public",
70
+ "createdAt": CREATED_AT,
71
+ }
72
+
73
+
74
+ def proposal_payload(*, id: int = 100, opportunity_id: int = 5, external_id: str = "ext-1") -> dict[str, Any]:
75
+ return {
76
+ "id": id,
77
+ "opportunityId": opportunity_id,
78
+ "externalId": external_id,
79
+ "versions": [],
80
+ "changemakers": [],
81
+ "createdAt": CREATED_AT,
82
+ "createdBy": CREATED_BY,
83
+ }
84
+
85
+
86
+ def initiative_payload(*, id: int = 1, changemaker_id: int = 10, title: str = "Summer meals") -> dict[str, Any]:
87
+ return {
88
+ "id": id,
89
+ "changemakerId": changemaker_id,
90
+ "title": title,
91
+ "createdAt": CREATED_AT,
92
+ "createdBy": CREATED_BY,
93
+ }
94
+
95
+
96
+ def initiative_field_value_payload(
97
+ *,
98
+ id: int = 1,
99
+ initiative_id: int = 1,
100
+ short_code: str = "field",
101
+ value: str = "",
102
+ created_at: str = CREATED_AT,
103
+ data_type: str = "string",
104
+ ) -> dict[str, Any]:
105
+ return {
106
+ "id": id,
107
+ "initiativeId": initiative_id,
108
+ "baseFieldShortCode": short_code,
109
+ "baseField": base_field_payload(short_code, data_type=data_type, category="project"),
110
+ "sourceId": 1,
111
+ "source": source_payload(),
112
+ "value": value,
113
+ "file": None,
114
+ "goodAsOf": None,
115
+ "isValid": True,
116
+ "createdAt": created_at,
117
+ "createdBy": CREATED_BY,
118
+ }
119
+
120
+
121
+ def changemaker_proposal_payload(*, id: int = 1, changemaker_id: int = 10, proposal_id: int = 100) -> dict[str, Any]:
122
+ return {
123
+ "id": id,
124
+ "changemakerId": changemaker_id,
125
+ "changemaker": changemaker_payload(id=changemaker_id),
126
+ "proposalId": proposal_id,
127
+ "proposal": proposal_payload(id=proposal_id),
128
+ "createdAt": CREATED_AT,
129
+ }
130
+
131
+
132
+ def organization_payload(
133
+ *,
134
+ changemaker: dict[str, Any] | None = None,
135
+ funder: dict[str, Any] | None = None,
136
+ data_provider: dict[str, Any] | None = None,
137
+ ) -> dict[str, Any]:
138
+ return {"changemaker": changemaker, "funder": funder, "dataProvider": data_provider}
139
+
140
+
141
+ def application_form_payload(*, id: int = 7, version: int = 1, opportunity_id: int = 5) -> dict[str, Any]:
142
+ return {
143
+ "id": id,
144
+ "version": version,
145
+ "opportunityId": opportunity_id,
146
+ "name": f"Application form {id}",
147
+ "fields": [],
148
+ "createdAt": CREATED_AT,
149
+ }
150
+
151
+
152
+ def source_payload(*, id: int = 1, label: str = "src") -> dict[str, Any]:
153
+ return {"id": id, "label": label, "createdAt": CREATED_AT}
154
+
155
+
156
+ def proposal_version_payload(*, id: int = 1, proposal_id: int = 100, version: int = 1) -> dict[str, Any]:
157
+ return {
158
+ "id": id,
159
+ "proposalId": proposal_id,
160
+ "sourceId": 1,
161
+ "source": source_payload(),
162
+ "applicationFormId": 7,
163
+ "version": version,
164
+ "fieldValues": [],
165
+ "createdAt": CREATED_AT,
166
+ "createdBy": CREATED_BY,
167
+ }
168
+
169
+
170
+ def changemaker_field_value_batch_payload(
171
+ *, id: int = 1, source_id: int = 1, notes: str | None = "Routine annual import"
172
+ ) -> dict[str, Any]:
173
+ return {
174
+ "id": id,
175
+ "sourceId": source_id,
176
+ "source": source_payload(id=source_id),
177
+ "notes": notes,
178
+ "createdBy": CREATED_BY,
179
+ "createdAt": CREATED_AT,
180
+ }
181
+
182
+
183
+ def changemaker_field_value_payload(
184
+ *,
185
+ id: int = 1,
186
+ changemaker_id: int = 10,
187
+ batch_id: int = 1,
188
+ short_code: str = "organization_name",
189
+ value: str = "Acme",
190
+ is_valid: bool | None = True,
191
+ batch: dict[str, Any] | None = None,
192
+ ) -> dict[str, Any]:
193
+ return {
194
+ "id": id,
195
+ "changemakerId": changemaker_id,
196
+ "batchId": batch_id,
197
+ "batch": batch if batch is not None else changemaker_field_value_batch_payload(id=batch_id),
198
+ "baseFieldShortCode": short_code,
199
+ "baseField": base_field_payload(short_code),
200
+ "value": value,
201
+ "goodAsOf": CREATED_AT,
202
+ "isValid": is_valid,
203
+ "file": None,
204
+ "createdAt": CREATED_AT,
205
+ }
206
+
207
+
208
+ def bundle(entries: list[dict[str, Any]], *, total: int | None = None) -> dict[str, Any]:
209
+ return {"entries": entries, "total": total if total is not None else len(entries)}
210
+
211
+
212
+ def add_json_response(
213
+ *,
214
+ base_url: str,
215
+ path: str,
216
+ payload: dict[str, Any] | list[Any],
217
+ status: int = 200,
218
+ query_params: dict[str, Any] | None = None,
219
+ ) -> None:
220
+ add_kwargs: dict[str, Any] = {
221
+ "method": responses.GET,
222
+ "url": f"{base_url.rstrip('/')}/{path.lstrip('/')}",
223
+ "json": payload,
224
+ "status": status,
225
+ }
226
+ if query_params is not None:
227
+ add_kwargs["match"] = [responses.matchers.query_param_matcher({k: str(v) for k, v in query_params.items()})]
228
+ responses.add(**add_kwargs)
229
+
230
+
231
+ def add_changemaker_response(
232
+ *, base_url: str, id: int = 1, status: int = 200, payload: dict[str, Any] | None = None, **payload_kwargs: Any
233
+ ) -> None:
234
+ add_json_response(
235
+ base_url=base_url,
236
+ path=f"changemakers/{id}",
237
+ payload=payload if payload is not None else changemaker_payload(id=id, **payload_kwargs),
238
+ status=status,
239
+ )
240
+
241
+
242
+ def add_funder_response(
243
+ *,
244
+ base_url: str,
245
+ short_code: str = "acme",
246
+ status: int = 200,
247
+ payload: dict[str, Any] | None = None,
248
+ **payload_kwargs: Any,
249
+ ) -> None:
250
+ add_json_response(
251
+ base_url=base_url,
252
+ path=f"funders/{short_code}",
253
+ payload=payload if payload is not None else funder_payload(short_code=short_code, **payload_kwargs),
254
+ status=status,
255
+ )
256
+
257
+
258
+ def add_proposal_response(
259
+ *, base_url: str, id: int = 100, status: int = 200, payload: dict[str, Any] | None = None, **payload_kwargs: Any
260
+ ) -> None:
261
+ add_json_response(
262
+ base_url=base_url,
263
+ path=f"proposals/{id}",
264
+ payload=payload if payload is not None else proposal_payload(id=id, **payload_kwargs),
265
+ status=status,
266
+ )
267
+
268
+
269
+ def add_application_form_response(
270
+ *, base_url: str, id: int = 7, status: int = 200, payload: dict[str, Any] | None = None, **payload_kwargs: Any
271
+ ) -> None:
272
+ add_json_response(
273
+ base_url=base_url,
274
+ path=f"applicationForms/{id}",
275
+ payload=payload if payload is not None else application_form_payload(id=id, **payload_kwargs),
276
+ status=status,
277
+ )
278
+
279
+
280
+ def add_organization_response(
281
+ *, base_url: str, keycloak_id: str, status: int = 200, payload: dict[str, Any] | None = None, **payload_kwargs: Any
282
+ ) -> None:
283
+ add_json_response(
284
+ base_url=base_url,
285
+ path=f"organizations/{keycloak_id}",
286
+ payload=payload if payload is not None else organization_payload(**payload_kwargs),
287
+ status=status,
288
+ )
289
+
290
+
291
+ def add_page_response(
292
+ bundle_type: type[PageableBundle],
293
+ *,
294
+ base_url: str,
295
+ payload: dict[str, Any],
296
+ page: int = 1,
297
+ count_per_page: int | None = None,
298
+ content: str | None = None,
299
+ status: int = 200,
300
+ extra_params: dict[str, Any] | None = None,
301
+ path_params: dict[str, Any] | None = None,
302
+ ) -> None:
303
+ query_params: dict[str, Any] = {"_page": page, "_count": count_per_page or bundle_type.default_page_size}
304
+ if content:
305
+ query_params["_content"] = content
306
+ if extra_params:
307
+ query_params.update(extra_params)
308
+ add_json_response(
309
+ base_url=base_url,
310
+ path=bundle_type.pdc_endpoint.format(**(path_params or {})),
311
+ payload=payload,
312
+ status=status,
313
+ query_params=query_params,
314
+ )
pdc_api/token.py ADDED
@@ -0,0 +1,69 @@
1
+ import time
2
+ from typing import Protocol, runtime_checkable
3
+
4
+ import requests
5
+
6
+ from pdc_api.errors import PDCServiceError, TokenRequestError
7
+
8
+
9
+ @runtime_checkable
10
+ class TokenProvider(Protocol):
11
+ def get_token(self) -> str: ...
12
+
13
+ def refresh_if_necessary(self) -> None: ...
14
+
15
+
16
+ class KeycloakClientCredentialsProvider:
17
+ def __init__(
18
+ self,
19
+ *,
20
+ server_url: str,
21
+ realm: str,
22
+ client_id: str,
23
+ client_secret: str,
24
+ timeout: float,
25
+ expiry_leeway_seconds: float = 30.0,
26
+ ) -> None:
27
+ self._token_url = f"{server_url.rstrip('/')}/realms/{realm}/protocol/openid-connect/token"
28
+ self._client_id = client_id
29
+ self._client_secret = client_secret
30
+ self._timeout = timeout
31
+ self._leeway = expiry_leeway_seconds
32
+ self._token: str | None = None
33
+ self._expires_at: float = 0.0
34
+
35
+ def get_token(self) -> str:
36
+ if self._token is None or time.monotonic() >= self._expires_at - self._leeway:
37
+ self._token, self._expires_at = self._request_token()
38
+ return self._token
39
+
40
+ def refresh_if_necessary(self) -> None:
41
+ pass
42
+
43
+ def _request_token(self) -> tuple[str, float]:
44
+ try:
45
+ response = requests.post(
46
+ self._token_url,
47
+ data={
48
+ "grant_type": "client_credentials",
49
+ "client_id": self._client_id,
50
+ "client_secret": self._client_secret,
51
+ },
52
+ timeout=self._timeout,
53
+ )
54
+ except requests.Timeout as exc:
55
+ raise PDCServiceError(detail="Request to PDC auth timed out") from exc
56
+ except requests.ConnectionError as exc:
57
+ raise PDCServiceError(detail="Could not connect to PDC auth") from exc
58
+ if response.status_code != 200:
59
+ try:
60
+ detail = response.json()
61
+ except ValueError:
62
+ detail = response.text
63
+ raise TokenRequestError(detail=detail, code=response.status_code)
64
+ # A fronting proxy can return 200 with a body that isn't a token.
65
+ try:
66
+ payload = response.json()
67
+ return payload["access_token"], time.monotonic() + payload["expires_in"]
68
+ except (ValueError, KeyError) as exc:
69
+ raise TokenRequestError(detail="Malformed token response from PDC auth", code=response.status_code) from exc
pdc_api/transport.py ADDED
@@ -0,0 +1,100 @@
1
+ from typing import Any
2
+ from urllib.parse import urljoin
3
+
4
+ import requests
5
+ from requests.adapters import HTTPAdapter
6
+ from urllib3.util import Retry
7
+
8
+ from pdc_api import errors
9
+ from pdc_api.token import TokenProvider
10
+
11
+ _ERRORS_BY_STATUS = {
12
+ 400: errors.PDCBadRequestError,
13
+ 401: errors.PDCUnauthorizedError,
14
+ 403: errors.PDCForbiddenError,
15
+ 404: errors.PDCNotFoundError,
16
+ 409: errors.PDCConflictError,
17
+ 422: errors.PDCUnprocessableEntityError,
18
+ }
19
+
20
+
21
+ class APISession:
22
+ def __init__(
23
+ self,
24
+ *,
25
+ base_url: str,
26
+ token_provider: TokenProvider,
27
+ timeout: float = 15,
28
+ request_kwargs: dict[str, Any] | None = None,
29
+ keep_alive: bool = True,
30
+ ) -> None:
31
+ # Without the trailing slash, urljoin drops the last path segment of a base like "https://host/api".
32
+ self._base_url = base_url if base_url.endswith("/") else base_url + "/"
33
+ self.auth = token_provider
34
+ self._timeout = timeout
35
+ self._request_kwargs = request_kwargs or {}
36
+ self._session = requests.Session()
37
+ self._session.headers["Accept"] = "application/json"
38
+ # A proxy in front of PDC can answer a healthy upstream with a one-off 502; only idempotent reads retry.
39
+ retries = Retry(
40
+ total=3,
41
+ backoff_factor=0.5,
42
+ status_forcelist=(502, 503, 504),
43
+ allowed_methods=("GET", "HEAD"),
44
+ raise_on_status=False,
45
+ )
46
+ for scheme in ("https://", "http://"):
47
+ self._session.mount(scheme, HTTPAdapter(max_retries=retries))
48
+ # Idle pooled connections can be closed server-side and raise RemoteDisconnected on reuse.
49
+ if not keep_alive:
50
+ self._session.headers["Connection"] = "close"
51
+
52
+ def _make_api_url(self, path: str) -> str:
53
+ return urljoin(self._base_url, path.lstrip("/"))
54
+
55
+ def _make_api_request(
56
+ self, method: str, url: str, data: Any = None, params: Any = None, **kwargs: Any
57
+ ) -> requests.Response:
58
+ if not url.startswith("http"):
59
+ url = self._make_api_url(url)
60
+ timeout = kwargs.pop("timeout", self._timeout)
61
+
62
+ self.auth.refresh_if_necessary()
63
+ self._session.headers["Authorization"] = f"Bearer {self.auth.get_token()}"
64
+
65
+ try:
66
+ response = self._session.request(
67
+ method, url, data=data, params=params, timeout=timeout, **{**self._request_kwargs, **kwargs}
68
+ )
69
+ except requests.Timeout as exc:
70
+ raise errors.PDCServiceError(detail="Request to PDC timed out") from exc
71
+ except requests.ConnectionError as exc:
72
+ raise errors.PDCServiceError(detail="Could not connect to PDC") from exc
73
+
74
+ if response.status_code >= 300:
75
+ try:
76
+ detail = response.json()
77
+ except ValueError:
78
+ detail = response.text or f"HTTP {response.status_code}"
79
+ error_class: type[errors.PDCException]
80
+ if response.status_code >= 500:
81
+ error_class = errors.PDCServiceError
82
+ else:
83
+ error_class = _ERRORS_BY_STATUS.get(response.status_code, errors.PDCException)
84
+ raise error_class(detail=detail, code=response.status_code)
85
+ return response
86
+
87
+ def get(self, path: str, **kwargs: Any) -> requests.Response:
88
+ return self._make_api_request("GET", path, **kwargs)
89
+
90
+ def put(self, path: str, **kwargs: Any) -> requests.Response:
91
+ return self._make_api_request("PUT", path, **kwargs)
92
+
93
+ def post(self, path: str, **kwargs: Any) -> requests.Response:
94
+ return self._make_api_request("POST", path, **kwargs)
95
+
96
+ def patch(self, path: str, **kwargs: Any) -> requests.Response:
97
+ return self._make_api_request("PATCH", path, **kwargs)
98
+
99
+ def delete(self, path: str, **kwargs: Any) -> requests.Response:
100
+ return self._make_api_request("DELETE", path, **kwargs)