-
Notifications
You must be signed in to change notification settings - Fork 9
[OSDEV-2266] [Partner Fields Enhancement] Add JSON Schema support for the Object type field #816
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
Merged
Changes from 24 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
e6bf7b7
implement draft logic to support json schema validation for partner f…
roman-stolar 244dfb0
added json formatting and validation for json schema field in admin p…
roman-stolar 751fb5e
fix issue with format validation
roman-stolar 70f3974
added django json editor
roman-stolar 3f312e6
small fix
roman-stolar 15bf5d9
updated cdn access to cloud front
roman-stolar 363b2cb
fix linter
roman-stolar 20727be
refactored
roman-stolar 88b4074
Merge commit 'b33cfd6b9226a103a79c14744de961202f596967' into OSDEV-22…
roman-stolar dab9528
fix linter
roman-stolar 122c35a
possible fix tests
roman-stolar 23aef81
small UI fixes
roman-stolar 36efc2d
fix json format for json_schema value
roman-stolar 97f11b6
Merge branch 'main' into OSDEV-2266-add-json-schema-support
roman-stolar bfcc208
properly save to db
roman-stolar 97d14ec
Merge branch 'main' into OSDEV-2266-add-json-schema-support
roman-stolar 8a029c1
fix linter
roman-stolar 32e55b1
Merge commit '97d14eca63d2eec766451e2b3a9263962016651f' into OSDEV-22…
roman-stolar b7e860d
added unit tests
roman-stolar 5ced5c7
possible fix
roman-stolar 0480492
fix tests
roman-stolar 64794f0
updated release notes
roman-stolar 30e0fad
remove head issue
roman-stolar 640c807
addressed Vadim comments
roman-stolar e1a581e
small fix
roman-stolar 4b11136
Merge branch 'main' into OSDEV-2266-add-json-schema-support
roman-stolar 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
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
19 changes: 19 additions & 0 deletions
19
src/django/api/migrations/0186_add_json_schema_to_partner_field.py
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,19 @@ | ||
| # Generated by Django 3.2.17 on 2025-01-18 12:00 | ||
|
|
||
| from django.db import migrations, models | ||
|
|
||
|
|
||
| class Migration(migrations.Migration): | ||
|
|
||
| dependencies = [ | ||
| ('api', '0185_add_source_by_to_partner_field'), | ||
| ] | ||
|
|
||
| operations = [ | ||
| migrations.AddField( | ||
| model_name='partnerfield', | ||
| name='json_schema', | ||
| field=models.JSONField(blank=True, null=True, help_text='JSON Schema for validating object type partner fields. Used when type is "object".'), | ||
| ), | ||
| ] | ||
|
|
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
218 changes: 218 additions & 0 deletions
218
...n_event_actions/creation/location_contribution/processors/partner_field_type_processor.py
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,218 @@ | ||
| import json | ||
| from typing import Dict, List, Mapping, Optional, Tuple | ||
|
|
||
| import jsonschema | ||
| from jsonschema.exceptions import ValidationError as JsonSchemaValidationError | ||
| from jsonschema.validators import Draft202012Validator | ||
| from rest_framework import status | ||
|
|
||
| from api.moderation_event_actions.creation.location_contribution \ | ||
| .processors.contribution_processor import ContributionProcessor | ||
| from api.moderation_event_actions.creation.dtos.create_moderation_event_dto \ | ||
| import CreateModerationEventDTO | ||
| from api.models.partner_field import PartnerField | ||
| from api.constants import APIV1CommonErrorMessages | ||
|
|
||
|
|
||
| class PartnerFieldTypeProcessor(ContributionProcessor): | ||
|
|
||
| TYPE_VALIDATORS = { | ||
| 'int': lambda value: isinstance(value, int) | ||
| and not isinstance(value, bool), | ||
| 'float': lambda value: isinstance(value, float) | ||
| and not isinstance(value, bool), | ||
| 'string': lambda value: isinstance(value, str), | ||
| 'object': lambda value: isinstance( | ||
| value, (dict, list) | ||
| ), | ||
| } | ||
|
|
||
| FORMAT_CHECKER = jsonschema.FormatChecker() | ||
|
|
||
| def process( | ||
| self, | ||
| event_dto: CreateModerationEventDTO | ||
| ) -> CreateModerationEventDTO: | ||
|
|
||
| raw = event_dto.raw_data or {} | ||
| if not raw: | ||
| return super().process(event_dto) | ||
|
|
||
| incoming_keys = set(raw.keys()) | ||
|
|
||
| partner_fields_qs = PartnerField.objects \ | ||
| .filter(name__in=incoming_keys) \ | ||
| .values("name", "type", "json_schema") | ||
| partner_fields_data: Dict[str, Dict] = { | ||
| field["name"]: { | ||
| "type": field["type"], | ||
| "json_schema": ( | ||
| PartnerFieldTypeProcessor.__parse_json_schema( | ||
| field["json_schema"] | ||
| ) | ||
| ) | ||
| } | ||
| for field in partner_fields_qs | ||
| } | ||
|
|
||
| if not partner_fields_data: | ||
| return super().process(event_dto) | ||
|
|
||
| validation_errors = self.__validate_partner_fields( | ||
| raw, | ||
| partner_fields_data | ||
| ) | ||
|
|
||
| if validation_errors: | ||
| event_dto.errors = self.__transform_validation_errors( | ||
| validation_errors | ||
| ) | ||
| event_dto.status_code = status.HTTP_422_UNPROCESSABLE_ENTITY | ||
| return event_dto | ||
|
|
||
| return super().process(event_dto) | ||
|
|
||
| @staticmethod | ||
| def __validate_partner_fields( | ||
| raw: Mapping[str, object], | ||
| partner_fields_data: Dict[str, Dict] | ||
| ) -> List[Tuple[str, str]]: | ||
|
|
||
| validation_errors: List[Tuple[str, str]] = [] | ||
|
|
||
| for field_name, field_info in partner_fields_data.items(): | ||
| value = raw.get(field_name) | ||
| if value is None: | ||
| continue | ||
|
|
||
| field_type = field_info.get("type") | ||
| json_schema = field_info.get("json_schema") | ||
|
|
||
| error = PartnerFieldTypeProcessor.__validate_single_field( | ||
| field_name, value, field_type, json_schema | ||
| ) | ||
| if error: | ||
| validation_errors.append(error) | ||
|
|
||
| return validation_errors | ||
|
|
||
| @staticmethod | ||
| def __validate_single_field( | ||
| field_name: str, | ||
| value: object, | ||
| field_type: str, | ||
| json_schema: object | ||
| ) -> Optional[Tuple[str, str]]: | ||
|
|
||
| use_json_schema = ( | ||
| field_type == PartnerField.OBJECT and json_schema | ||
| ) | ||
|
|
||
| if use_json_schema: | ||
| return PartnerFieldTypeProcessor.__validate_with_json_schema( | ||
| field_name, value, json_schema | ||
| ) | ||
|
|
||
| return PartnerFieldTypeProcessor.__validate_with_type_validator( | ||
| field_name, value, field_type | ||
| ) | ||
roman-stolar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| @staticmethod | ||
| def __validate_with_json_schema( | ||
| field_name: str, | ||
| value: object, | ||
| json_schema: object | ||
| ) -> Optional[Tuple[str, str]]: | ||
|
|
||
| try: | ||
| validator = Draft202012Validator( | ||
| schema=json_schema, | ||
| format_checker=PartnerFieldTypeProcessor.FORMAT_CHECKER | ||
| ) | ||
| validator.validate(instance=value) | ||
| return None | ||
| except JsonSchemaValidationError as e: | ||
| error_message = PartnerFieldTypeProcessor \ | ||
| .__format_json_schema_error( | ||
| e | ||
| ) | ||
| return (field_name, error_message) | ||
| except Exception as e: | ||
| return (field_name, f"Schema validation error: {str(e)}") | ||
|
|
||
roman-stolar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| @staticmethod | ||
| def __format_json_schema_error( | ||
| error: JsonSchemaValidationError | ||
| ) -> str: | ||
|
|
||
| error_message = error.message | ||
| error_path = PartnerFieldTypeProcessor.__extract_error_path(error) | ||
|
|
||
| if error_path: | ||
| return f"{error_path}: {error_message}" | ||
|
|
||
| return error_message | ||
|
|
||
| @staticmethod | ||
| def __extract_error_path( | ||
| error: JsonSchemaValidationError | ||
| ) -> Optional[str]: | ||
|
|
||
| if hasattr(error, 'absolute_path') and error.absolute_path: | ||
| return ".".join(str(p) for p in error.absolute_path) | ||
|
|
||
| if hasattr(error, 'path') and error.path: | ||
| return ".".join(str(p) for p in error.path) | ||
|
|
||
| return None | ||
|
|
||
| @staticmethod | ||
| def __validate_with_type_validator( | ||
| field_name: str, | ||
| value: object, | ||
| field_type: str | ||
| ) -> Optional[Tuple[str, str]]: | ||
|
|
||
| if field_type not in PartnerFieldTypeProcessor.TYPE_VALIDATORS: | ||
| return None | ||
|
|
||
| validator = PartnerFieldTypeProcessor.TYPE_VALIDATORS[field_type] | ||
| if validator(value): | ||
| return None | ||
|
|
||
| return ( | ||
| field_name, | ||
| f'Field {field_name} must be {field_type}, ' | ||
| f'not {type(value).__name__}.' | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def __parse_json_schema(json_schema: object) -> Optional[dict]: | ||
| if json_schema is None: | ||
| return None | ||
|
|
||
| if isinstance(json_schema, dict): | ||
| return json_schema | ||
|
|
||
| if isinstance(json_schema, str): | ||
| try: | ||
| return json.loads(json_schema) | ||
| except (json.JSONDecodeError, TypeError): | ||
| return None | ||
|
|
||
| return None | ||
|
|
||
| @staticmethod | ||
| def __transform_validation_errors( | ||
| validation_errors: List[Tuple[str, str]] | ||
| ) -> Dict: | ||
| return { | ||
| 'detail': APIV1CommonErrorMessages.COMMON_REQ_BODY_ERROR, | ||
| 'errors': [ | ||
| { | ||
| 'field': field_name, | ||
| 'detail': error_message, | ||
| } | ||
| for field_name, error_message in validation_errors | ||
| ], | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.