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/client.py ADDED
@@ -0,0 +1,332 @@
1
+ import json
2
+ from collections.abc import Generator
3
+ from datetime import datetime
4
+ from typing import Any, ClassVar, Protocol, Self
5
+
6
+ import requests
7
+
8
+ from pdc_api import errors
9
+ from pdc_api.models import (
10
+ BaseField,
11
+ Changemaker,
12
+ ChangemakerApplicationForm,
13
+ ChangemakerFieldValue,
14
+ ChangemakerFieldValueBatch,
15
+ ChangemakerProposal,
16
+ DataProvider,
17
+ File,
18
+ Funder,
19
+ Initiative,
20
+ InitiativeFieldValue,
21
+ NewProposalVersion,
22
+ Organization,
23
+ PresignedPost,
24
+ Proposal,
25
+ ProposalVersion,
26
+ Source,
27
+ )
28
+ from pdc_api.transport import APISession
29
+
30
+
31
+ def _iterate_pages(
32
+ session: APISession,
33
+ *,
34
+ endpoint: str,
35
+ params: dict[str, Any] | None = None,
36
+ count_per_page: int = 50,
37
+ max_requests: int | None = None,
38
+ **kwargs: Any,
39
+ ) -> Generator[dict[str, Any], None, None]:
40
+ params = params or {}
41
+ page = 1
42
+ n_pages = None
43
+ while n_pages is None or page <= n_pages:
44
+ params.update({"_page": page, "_count": count_per_page})
45
+ response = session.get(endpoint, params=params, **kwargs)
46
+ payload = response.json()
47
+ if n_pages is None:
48
+ total = payload["total"]
49
+ n_pages = (total + count_per_page - 1) // count_per_page
50
+ yield payload
51
+ page += 1
52
+ if max_requests is not None and page > max_requests:
53
+ break
54
+ if "entries" in payload and len(payload["entries"]) < count_per_page:
55
+ # A short page is the last one, even if "total" disagrees.
56
+ break
57
+
58
+
59
+ def get_base_fields(session: APISession) -> list[BaseField]:
60
+ return [
61
+ BaseField.model_validate(entry)
62
+ for payload in _iterate_pages(session, endpoint="baseFields", count_per_page=10_000)
63
+ for entry in payload["entries"]
64
+ ]
65
+
66
+
67
+ def get_changemakers(session: APISession) -> Generator[Changemaker, None, None]:
68
+ for payload in _iterate_pages(session, endpoint="changemakers"):
69
+ for entry in payload["entries"]:
70
+ yield Changemaker.model_validate(entry)
71
+
72
+
73
+ def get_funders(session: APISession) -> Generator[Funder, None, None]:
74
+ for payload in _iterate_pages(session, endpoint="funders"):
75
+ for entry in payload["entries"]:
76
+ yield Funder.model_validate(entry)
77
+
78
+
79
+ def get_data_providers(session: APISession) -> Generator[DataProvider, None, None]:
80
+ for payload in _iterate_pages(session, endpoint="dataProviders"):
81
+ for entry in payload["entries"]:
82
+ yield DataProvider.model_validate(entry)
83
+
84
+
85
+ def get_changemaker_proposals(
86
+ session: APISession,
87
+ *,
88
+ changemaker_id: int | None = None,
89
+ proposal_id: int | None = None,
90
+ count_per_page: int | None = None,
91
+ ) -> Generator[ChangemakerProposal, None, None]:
92
+ endpoint = "changemakerProposals"
93
+ query_params = {}
94
+ if changemaker_id is not None:
95
+ query_params["changemaker"] = changemaker_id
96
+ if proposal_id is not None:
97
+ query_params["proposal"] = proposal_id
98
+
99
+ page_kwargs = {} if count_per_page is None else {"count_per_page": count_per_page}
100
+ for payload in _iterate_pages(session, endpoint=endpoint, params=query_params, **page_kwargs):
101
+ for entry in payload["entries"]:
102
+ yield ChangemakerProposal.model_validate(entry)
103
+
104
+
105
+ def get_proposals(session: APISession, *, count_per_page: int = 50) -> Generator[Proposal, None, None]:
106
+ for payload in _iterate_pages(session, endpoint="proposals", count_per_page=count_per_page):
107
+ for entry in payload["entries"]:
108
+ yield Proposal.model_validate(entry)
109
+
110
+
111
+ def get_initiatives(session: APISession, *, changemaker_id: int | None = None) -> Generator[Initiative, None, None]:
112
+ params = {} if changemaker_id is None else {"changemaker": changemaker_id}
113
+ for payload in _iterate_pages(session, endpoint="initiatives", params=params):
114
+ for entry in payload["entries"]:
115
+ yield Initiative.model_validate(entry)
116
+
117
+
118
+ def get_initiative(session: APISession, *, initiative_id: int) -> Initiative:
119
+ response = session.get(f"initiatives/{initiative_id}")
120
+ return Initiative.model_validate(response.json())
121
+
122
+
123
+ def get_initiative_field_values(
124
+ session: APISession, *, initiative_id: int
125
+ ) -> Generator[InitiativeFieldValue, None, None]:
126
+ for payload in _iterate_pages(session, endpoint=f"initiatives/{initiative_id}/fieldValues"):
127
+ for entry in payload["entries"]:
128
+ yield InitiativeFieldValue.model_validate(entry)
129
+
130
+
131
+ def _good_as_of_json(good_as_of: datetime | None) -> str | None:
132
+ if good_as_of is None:
133
+ return None
134
+ if good_as_of.tzinfo is None:
135
+ raise ValueError("good_as_of must include a timezone")
136
+ return good_as_of.isoformat()
137
+
138
+
139
+ def create_initiative(session: APISession, *, changemaker_id: int, title: str) -> Initiative:
140
+ response = session.post("initiatives", json={"changemakerId": changemaker_id, "title": title})
141
+ return Initiative.model_validate(response.json())
142
+
143
+
144
+ def create_initiative_field_value(
145
+ session: APISession,
146
+ *,
147
+ initiative_id: int,
148
+ base_field_short_code: str,
149
+ value: str,
150
+ source_id: int,
151
+ good_as_of: datetime | None = None,
152
+ ) -> InitiativeFieldValue:
153
+ response = session.post(
154
+ f"initiatives/{initiative_id}/fieldValues",
155
+ json={
156
+ "baseFieldShortCode": base_field_short_code,
157
+ "value": value,
158
+ "sourceId": source_id,
159
+ "goodAsOf": _good_as_of_json(good_as_of),
160
+ },
161
+ )
162
+ return InitiativeFieldValue.model_validate(response.json())
163
+
164
+
165
+ def get_organization_by_keycloak_id(session: APISession, *, keycloak_id: str) -> Organization:
166
+ response = session.get(f"organizations/{keycloak_id}")
167
+ return Organization.model_validate(response.json())
168
+
169
+
170
+ def get_application_form(session: APISession, *, application_form_id: int) -> ChangemakerApplicationForm:
171
+ response = session.get(f"applicationForms/{application_form_id}")
172
+ return ChangemakerApplicationForm.model_validate(response.json())
173
+
174
+
175
+ def get_application_form_by_name(session: APISession, *, name: str) -> ChangemakerApplicationForm:
176
+ for payload in _iterate_pages(session, endpoint="applicationForms"):
177
+ for entry in payload["entries"]:
178
+ if entry["name"] == name:
179
+ return ChangemakerApplicationForm.model_validate(entry)
180
+ raise errors.ApplicationFormNotFoundError(detail=f"No application form named {name!r}")
181
+
182
+
183
+ def create_proposal(session: APISession, *, data: dict[str, Any]) -> Proposal:
184
+ response = session.post("proposals", json=data)
185
+ return Proposal.model_validate(response.json())
186
+
187
+
188
+ def create_proposal_version(session: APISession, *, proposal_version: NewProposalVersion) -> ProposalVersion:
189
+ response = session.post("proposalVersions", json=json.loads(proposal_version.model_dump_json(by_alias=True)))
190
+ return ProposalVersion.model_validate(response.json())
191
+
192
+
193
+ def link_changemaker_to_proposal(session: APISession, *, changemaker_id: int, proposal_id: int) -> ChangemakerProposal:
194
+ response = session.post("changemakerProposals", json={"changemakerId": changemaker_id, "proposalId": proposal_id})
195
+ return ChangemakerProposal.model_validate(response.json())
196
+
197
+
198
+ def get_changemaker_proposal(session: APISession, *, proposal_id: int) -> ChangemakerProposal:
199
+ response = session.get("changemakerProposals", params={"proposal": proposal_id})
200
+ try:
201
+ return ChangemakerProposal.model_validate(response.json()["entries"][0])
202
+ except (KeyError, IndexError):
203
+ raise errors.ProposalNotFoundError(detail=f"No changemaker linked to proposal {proposal_id}") from None
204
+
205
+
206
+ def get_proposal(session: APISession, *, proposal_id: int) -> Proposal:
207
+ try:
208
+ response = session.get(f"proposals/{proposal_id}")
209
+ except errors.PDCNotFoundError as exc:
210
+ raise errors.ProposalNotFoundError(detail=f"No proposal with id {proposal_id}", code=exc.code) from exc
211
+ return Proposal.model_validate(response.json())
212
+
213
+
214
+ def get_changemaker(session: APISession, *, changemaker_id: int) -> Changemaker:
215
+ try:
216
+ response = session.get(f"changemakers/{changemaker_id}")
217
+ return Changemaker.model_validate(response.json())
218
+ except errors.PDCNotFoundError as exc:
219
+ raise errors.ChangemakerNotFoundError(detail=f"No changemaker with id {changemaker_id}", code=exc.code) from exc
220
+
221
+
222
+ def get_changemaker_field_values(
223
+ session: APISession,
224
+ *,
225
+ changemaker_id: int | None = None,
226
+ batch_id: int | None = None,
227
+ ) -> Generator[ChangemakerFieldValue, None, None]:
228
+ params = {}
229
+ if changemaker_id is not None:
230
+ params["changemaker"] = changemaker_id
231
+ if batch_id is not None:
232
+ params["changemakerFieldValueBatch"] = batch_id
233
+ for payload in _iterate_pages(session, endpoint="changemakerFieldValues", params=params):
234
+ for entry in payload["entries"]:
235
+ yield ChangemakerFieldValue.model_validate(entry)
236
+
237
+
238
+ def get_changemaker_field_value_batch(session: APISession, *, batch_id: int) -> ChangemakerFieldValueBatch:
239
+ try:
240
+ response = session.get(f"changemakerFieldValueBatches/{batch_id}")
241
+ except errors.PDCNotFoundError as exc:
242
+ raise errors.ChangemakerFieldValueBatchNotFoundError(
243
+ detail=f"No changemaker field value batch with id {batch_id}", code=exc.code
244
+ ) from exc
245
+ return ChangemakerFieldValueBatch.model_validate(response.json())
246
+
247
+
248
+ def create_changemaker_source(session: APISession, *, changemaker_id: int, label: str) -> Source:
249
+ response = session.post("sources", json={"changemakerId": changemaker_id, "label": label})
250
+ return Source.model_validate(response.json())
251
+
252
+
253
+ def create_changemaker_field_value_batch(
254
+ session: APISession, *, source_id: int, notes: str | None = None
255
+ ) -> ChangemakerFieldValueBatch:
256
+ response = session.post("changemakerFieldValueBatches", json={"sourceId": source_id, "notes": notes})
257
+ return ChangemakerFieldValueBatch.model_validate(response.json())
258
+
259
+
260
+ def create_changemaker_field_value(
261
+ session: APISession,
262
+ *,
263
+ changemaker_id: int,
264
+ base_field_short_code: str,
265
+ batch_id: int,
266
+ value: str,
267
+ good_as_of: datetime | None = None,
268
+ ) -> ChangemakerFieldValue:
269
+ response = session.post(
270
+ "changemakerFieldValues",
271
+ json={
272
+ "changemakerId": changemaker_id,
273
+ "baseFieldShortCode": base_field_short_code,
274
+ "batchId": batch_id,
275
+ "value": value,
276
+ "goodAsOf": _good_as_of_json(good_as_of),
277
+ },
278
+ )
279
+ return ChangemakerFieldValue.model_validate(response.json())
280
+
281
+
282
+ def get_funder(session: APISession, *, short_code: str) -> Funder:
283
+ try:
284
+ response = session.get(f"funders/{short_code}")
285
+ except errors.PDCNotFoundError as exc:
286
+ raise errors.FunderNotFoundError(detail=f"No funder with short code {short_code!r}", code=exc.code) from exc
287
+ return Funder.model_validate(response.json())
288
+
289
+
290
+ class PageableBundle(Protocol):
291
+ pdc_endpoint: ClassVar[str]
292
+ default_page_size: ClassVar[int]
293
+
294
+ @classmethod
295
+ def model_validate(cls, obj: Any) -> Self: ...
296
+
297
+
298
+ def get_bundle_page[BundleT: PageableBundle](
299
+ session: APISession,
300
+ bundle_type: type[BundleT],
301
+ *,
302
+ page: int = 1,
303
+ count_per_page: int | None = None,
304
+ content: str | None = None,
305
+ extra_params: dict[str, Any] | None = None,
306
+ path_params: dict[str, Any] | None = None,
307
+ ) -> BundleT:
308
+ params: dict[str, Any] = {"_page": page, "_count": count_per_page or bundle_type.default_page_size}
309
+ if content:
310
+ params["_content"] = content
311
+ if extra_params:
312
+ params.update(extra_params)
313
+ endpoint = bundle_type.pdc_endpoint.format(**(path_params or {}))
314
+ response = session.get(endpoint, params=params)
315
+ return bundle_type.model_validate(response.json())
316
+
317
+
318
+ def create_file(session: APISession, *, name: str, mime_type: str, size: int) -> File:
319
+ response = session.post("files", json={"name": name, "mimeType": mime_type, "size": size})
320
+ return File.model_validate(response.json())
321
+
322
+
323
+ def upload_file_to_s3_presigned_url(
324
+ *, presigned_post: PresignedPost, file_data: bytes, file_name: str, content_type: str
325
+ ) -> None:
326
+ fields = {**presigned_post.fields, "Content-Type": content_type}
327
+ files = {"file": (file_name, file_data, content_type)}
328
+ try:
329
+ response = requests.post(presigned_post.url, data=fields, files=files, timeout=120)
330
+ response.raise_for_status()
331
+ except requests.RequestException as exc:
332
+ raise errors.PDCServiceError(detail=f"Could not upload file to S3: {exc}") from exc
pdc_api/errors.py ADDED
@@ -0,0 +1,61 @@
1
+ from typing import Any
2
+
3
+
4
+ class PDCException(Exception):
5
+ def __init__(self, *, detail: Any, code: int | None = None) -> None:
6
+ super().__init__(str(detail))
7
+ self.detail = detail
8
+ self.code = code
9
+
10
+
11
+ class PDCBadRequestError(PDCException):
12
+ pass
13
+
14
+
15
+ class PDCUnauthorizedError(PDCException):
16
+ pass
17
+
18
+
19
+ class PDCForbiddenError(PDCException):
20
+ pass
21
+
22
+
23
+ class PDCServiceError(PDCException):
24
+ pass
25
+
26
+
27
+ # PDC returns 404 rather than 403 for a resource the caller may not view.
28
+ class PDCNotFoundError(PDCException):
29
+ pass
30
+
31
+
32
+ class PDCConflictError(PDCException):
33
+ pass
34
+
35
+
36
+ class PDCUnprocessableEntityError(PDCException):
37
+ pass
38
+
39
+
40
+ class TokenRequestError(PDCException):
41
+ pass
42
+
43
+
44
+ class ProposalNotFoundError(PDCNotFoundError):
45
+ pass
46
+
47
+
48
+ class ChangemakerNotFoundError(PDCNotFoundError):
49
+ pass
50
+
51
+
52
+ class ChangemakerFieldValueBatchNotFoundError(PDCNotFoundError):
53
+ pass
54
+
55
+
56
+ class FunderNotFoundError(PDCNotFoundError):
57
+ pass
58
+
59
+
60
+ class ApplicationFormNotFoundError(PDCNotFoundError):
61
+ pass
pdc_api/models.py ADDED
@@ -0,0 +1,136 @@
1
+ from datetime import datetime
2
+ from typing import ClassVar
3
+
4
+ from pydantic import Field
5
+
6
+ from pdc_api import _generated
7
+ from pdc_api._base import BaseSchema
8
+ from pdc_api._generated import (
9
+ ApplicationForm as ChangemakerApplicationForm,
10
+ )
11
+ from pdc_api._generated import (
12
+ ApplicationFormField,
13
+ BaseField,
14
+ BaseFieldCategory,
15
+ BaseFieldLocalization,
16
+ Changemaker,
17
+ ChangemakerFieldValue,
18
+ ChangemakerFieldValueBatch,
19
+ ChangemakerProposal,
20
+ DataProvider,
21
+ File,
22
+ Funder,
23
+ FunderCollaborativeMember,
24
+ Initiative,
25
+ InitiativeFieldValue,
26
+ Opportunity,
27
+ Organization,
28
+ PermissionGrantEntityType,
29
+ PermissionGrantGranteeType,
30
+ PermissionGrantVerb,
31
+ PresignedPost,
32
+ Proposal,
33
+ ProposalFieldValue,
34
+ ProposalVersion,
35
+ S3Bucket,
36
+ SensitivityClassification,
37
+ ShallowChangemaker,
38
+ Source,
39
+ )
40
+ from pdc_api._generated import (
41
+ ApplicationFormFieldInputType as InputType,
42
+ )
43
+ from pdc_api._generated import (
44
+ DataType as BaseFieldDataType,
45
+ )
46
+
47
+ __all__ = [
48
+ "ApplicationFormField",
49
+ "BaseField",
50
+ "BaseFieldCategory",
51
+ "BaseFieldDataType",
52
+ "BaseFieldLocalization",
53
+ "BaseSchema",
54
+ "Changemaker",
55
+ "ChangemakerApplicationForm",
56
+ "ChangemakerBundle",
57
+ "ChangemakerFieldValue",
58
+ "ChangemakerFieldValueBatch",
59
+ "ChangemakerProposal",
60
+ "ChangemakerProposalBundle",
61
+ "DataProvider",
62
+ "File",
63
+ "Funder",
64
+ "FunderBundle",
65
+ "FunderCollaborativeMember",
66
+ "FunderCollaborativeMemberBundle",
67
+ "Initiative",
68
+ "InitiativeBundle",
69
+ "InitiativeFieldValue",
70
+ "InputType",
71
+ "NewProposalFieldValue",
72
+ "NewProposalVersion",
73
+ "Opportunity",
74
+ "OpportunityBundle",
75
+ "Organization",
76
+ "PermissionGrantEntityType",
77
+ "PermissionGrantGranteeType",
78
+ "PermissionGrantVerb",
79
+ "PresignedPost",
80
+ "Proposal",
81
+ "ProposalBundle",
82
+ "ProposalFieldValue",
83
+ "ProposalVersion",
84
+ "S3Bucket",
85
+ "SensitivityClassification",
86
+ "ShallowChangemaker",
87
+ "Source",
88
+ ]
89
+
90
+
91
+ class ChangemakerBundle(_generated.ChangemakerBundle):
92
+ pdc_endpoint: ClassVar[str] = "changemakers"
93
+ default_page_size: ClassVar[int] = 10
94
+
95
+
96
+ class FunderBundle(_generated.FunderBundle):
97
+ pdc_endpoint: ClassVar[str] = "funders"
98
+ default_page_size: ClassVar[int] = 10
99
+
100
+
101
+ class FunderCollaborativeMemberBundle(_generated.FunderCollaborativeMemberBundle):
102
+ pdc_endpoint: ClassVar[str] = "funders/{funder_collaborative_short_code}/members"
103
+ default_page_size: ClassVar[int] = 50
104
+
105
+
106
+ class ProposalBundle(_generated.ProposalBundle):
107
+ pdc_endpoint: ClassVar[str] = "proposals"
108
+ default_page_size: ClassVar[int] = 10
109
+
110
+
111
+ class InitiativeBundle(_generated.InitiativeBundle):
112
+ pdc_endpoint: ClassVar[str] = "initiatives"
113
+ default_page_size: ClassVar[int] = 10
114
+
115
+
116
+ class OpportunityBundle(_generated.OpportunityBundle):
117
+ pdc_endpoint: ClassVar[str] = "opportunities"
118
+ default_page_size: ClassVar[int] = 10
119
+
120
+
121
+ ChangemakerProposalBundle = _generated.ChangemakerProposalBundle
122
+
123
+
124
+ # The spec defines these only as inline request bodies, so codegen does not emit them.
125
+ class NewProposalFieldValue(BaseSchema):
126
+ application_form_field_id: int = Field(alias="applicationFormFieldId")
127
+ position: int
128
+ value: str
129
+ good_as_of: datetime | None = Field(None, alias="goodAsOf")
130
+
131
+
132
+ class NewProposalVersion(BaseSchema):
133
+ proposal_id: int = Field(alias="proposalId")
134
+ source_id: int = Field(alias="sourceId")
135
+ application_form_id: int = Field(alias="applicationFormId")
136
+ field_values: list[NewProposalFieldValue] = Field(alias="fieldValues")