-
Notifications
You must be signed in to change notification settings - Fork 4
Refactor dg api model to pydantic #522 #523
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
joshdimanteto
merged 18 commits into
develop
from
refactor-dg-api-model-to-pydantic-522
Mar 16, 2026
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
7284f0d
Improve pydantic models #520
joshdimanteto 24be733
Merge branch 'upgrade-to-pydantic-V2-#520' into refactor-dg-api-model…
joshdimanteto f0b4bf6
refactor: datagateway api model to use pydantic V2 #522
joshdimanteto d9bd46f
use endpoint_dict for swagger #522
joshdimanteto d53c565
Auto generated pydantic using ICAT entity type #519
joshdimanteto 2492b49
add docstring to build_models #522
joshdimanteto cc387dc
Fix minor bugs
joshdimanteto 6a04939
Merge branch 'upgrade-to-pydantic-V2-#520' into refactor-dg-api-model…
joshdimanteto 6896015
make the relational fields optional on schemas #522
joshdimanteto 1f4707f
Merge branch 'upgrade-to-pydantic-V2-#520' into refactor-dg-api-model…
joshdimanteto 57cb6fb
fix linting and failing integration test #522
joshdimanteto 6153cf2
Make all field value schema optional #522
joshdimanteto 7a007ee
fix linting #522
joshdimanteto edfcce6
Merge branch 'upgrade-to-pydantic-V2-#520' into refactor-dg-api-model…
joshdimanteto bf4bd8a
Address review comments #522
joshdimanteto 40b50da
Merge branch 'upgrade-to-pydantic-V2-#520' into refactor-dg-api-model…
joshdimanteto e8e0b9f
Merge branch 'upgrade-to-pydantic-V2-#520' into refactor-dg-api-model…
joshdimanteto bf6083f
Merge branch 'upgrade-to-pydantic-V2-#520' into refactor-dg-api-model…
joshdimanteto File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| from datetime import datetime | ||
| import logging | ||
| from typing import Annotated, List, Optional, Union | ||
|
|
||
| from icat.exception import ICATError | ||
| from pydantic import BaseModel, create_model, Field | ||
|
|
||
| from datagateway_api.src.common.exceptions import PythonICATError | ||
| from datagateway_api.src.datagateway_api.icat.helpers import get_cached_client | ||
|
|
||
| log = logging.getLogger() | ||
|
|
||
|
|
||
| TYPE_MAP = { | ||
| "String": str, | ||
| "Long": int, | ||
| "Date": str, | ||
| "Boolean": bool, | ||
| "Double": float, | ||
| } | ||
|
|
||
| SYSTEM_FIELDS = { | ||
| "id", | ||
| "createId", | ||
| "modId", | ||
| "createTime", | ||
| "modTime", | ||
| } | ||
|
|
||
|
|
||
| class ICATId(BaseModel): | ||
| id_: Annotated[Optional[int], Field(None, alias="id")] | ||
|
|
||
|
|
||
| class ICATBaseEntity(ICATId): | ||
| create_id: Annotated[Optional[str], Field(None, alias="createId")] | ||
| create_time: Annotated[Optional[datetime], Field(None, alias="createTime")] | ||
| mod_id: Annotated[Optional[str], Field(None, alias="modId")] | ||
| mod_time: Annotated[Optional[datetime], Field(None, alias="modTime")] | ||
|
|
||
|
|
||
| def build_datagateway_api_model(**kwargs): | ||
| """ | ||
| Dynamically construct Pydantic models for all ICAT entities exposed by the | ||
| connected ICAT server. | ||
|
|
||
| This function queries the ICAT server for its schema (entity names, fields, | ||
| types, relationships, and nullability) and generates a set of Pydantic | ||
| models representing: | ||
|
|
||
| - The base entity model for each ICAT entity (e.g. `Investigation`) | ||
| - A corresponding POST model for creation (e.g. `InvestigationPost`) | ||
| - A corresponding PATCH model for partial updates (e.g. `InvestigationPatch`) | ||
|
|
||
| Relationship fields (ONE or MANY) are converted into either model references | ||
| or lists of ICAT IDs. Attribute fields are mapped to Python/Pydantic primitive | ||
| types according to the TYPE_MAP. Optionality and nullability are not strictly | ||
| preserved for all generated fields, as values support the distinct filter | ||
| operator, which may request one or many values from a given object. Field | ||
| descriptions from ICAT, when available, are carried over into the model metadata. | ||
|
|
||
| All generated models are finally rebuilt (`model_rebuild`) using the full | ||
| model namespace so that forward references between models resolve correctly. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| **kwargs : | ||
| Optional configuration parameters. Expected keys: | ||
| - `client_pool`: A pool or cache of ICAT clients, passed into | ||
| `get_cached_client`. | ||
|
|
||
| Returns | ||
| ------- | ||
| dict | ||
| A dictionary mapping model names (e.g. `"Investigation"`, | ||
| `"InvestigationPost"`, `"InvestigationPatch"`) to their corresponding | ||
| dynamically generated Pydantic model classes. | ||
|
|
||
| Raises | ||
| ------ | ||
| PythonICATError | ||
| If the ICAT server reports an error while fetching entity names or | ||
| entity schema information. | ||
|
|
||
| Notes | ||
| ----- | ||
| - Models include metadata (via `Annotated[... , Field(...)]`) for descriptions. | ||
| - SYSTEM_FIELDS are always excluded from the generated models. | ||
| - Relationship fields use forward references and are resolved at the end of | ||
| generation. | ||
| - The POST and PATCH models differ by optionality and update semantics. | ||
|
|
||
| """ | ||
|
|
||
| log.info("Building datagateway models") | ||
|
|
||
| datagateway_api_models = {} | ||
|
|
||
| client_pool = kwargs.get("client_pool") | ||
| client = get_cached_client(None, client_pool) | ||
|
|
||
| try: | ||
| entity_names = client.getEntityNames() | ||
| except ICATError as e: | ||
| raise PythonICATError(e) from e | ||
|
|
||
| for name in entity_names: | ||
| info = client.getEntityInfo(name) | ||
| fields = {} | ||
| post_fields = {} | ||
| post_name = f"{name}Post" | ||
| patch_name = f"{name}Patch" | ||
| for field in info.fields: | ||
|
|
||
| if field.name in SYSTEM_FIELDS: | ||
| continue | ||
|
|
||
| if field.relType == "ATTRIBUTE": | ||
| field_type = TYPE_MAP.get(field.type, str) | ||
| optional_field_type = Optional[field_type] | ||
|
|
||
| description = getattr(field, "comment", None) | ||
| field_metadata = Field(description=description) | ||
| optional_annotated_type = Annotated[optional_field_type, field_metadata] | ||
|
|
||
| fields[field.name] = (optional_annotated_type, None) | ||
| post_fields[field.name] = (optional_annotated_type, None) | ||
|
|
||
| else: | ||
| rel_model_name = field.type | ||
| if field.relType == "MANY": | ||
| rel_type_str = f"List['{rel_model_name}']" # noqa: B907 | ||
| post_type = f"List['{rel_model_name}Post']" # noqa: B907 | ||
| else: | ||
| rel_type_str = f"'{rel_model_name}'" # noqa: B907 | ||
| post_type = int | ||
|
|
||
| optional_type = Optional[post_type] | ||
| rel_type_str = f"Optional[{rel_type_str}]" | ||
|
|
||
| description = getattr(field, "comment", None) | ||
| field_metadata = Field(description=description) | ||
| annotated_type = Annotated[rel_type_str, field_metadata] | ||
| optional_annotated_type = Annotated[optional_type, field_metadata] | ||
| fields[field.name] = (annotated_type, None) | ||
| post_fields[field.name] = (optional_annotated_type, None) | ||
|
|
||
| model = create_model(name, __base__=ICATBaseEntity, **fields) | ||
| post_model = create_model(post_name, **post_fields) | ||
| patch_model = create_model(patch_name, __base__=ICATId, **post_fields) | ||
| datagateway_api_models[name] = model | ||
| datagateway_api_models[post_name] = post_model | ||
| datagateway_api_models[patch_name] = patch_model | ||
|
|
||
| for model in datagateway_api_models.values(): | ||
| types_namespace = { | ||
| **datagateway_api_models, | ||
| "List": List, | ||
| "Optional": Optional, | ||
| "Union": Union, | ||
| } | ||
| model.model_rebuild(_types_namespace=types_namespace) | ||
|
|
||
| log.info("Finished building all datagateway models") | ||
| return datagateway_api_models |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is fix in #519