I am trying to create a limited set of Pydantic models from a boto3 response (specifically CodeDeploy's get_deployment). Where I'm having trouble is this:
'revision': {
'revisionType': 'S3'|'GitHub'|'String'|'AppSpecContent',
's3Location': {
'bucket': 'string',
'key': 'string',
'bundleType': 'tar'|'tgz'|'zip'|'YAML'|'JSON',
'version': 'string',
'eTag': 'string'
},
'gitHubLocation': {
'repository': 'string',
'commitId': 'string'
},
'string': {
'content': 'string',
'sha256': 'string'
},
'appSpecContent': {
'content': 'string',
'sha256': 'string'
}
}
I have tried a discriminated union, but I'm missing something
class GitHubRevision(BaseModel):
revisionType: Literal['GitHub']
repository: str
commitId: str
class StringRevision(BaseModel):
revisionType: Literal['String']
class RevisionModel(BaseModel):
revision: Union[StringRevision, GitHubRevision]= Field(..., discriminator='revisionType')
data = {
'revisionType': 'GitHub',
'gitHubLocation': {
'repository': 'aaa',
'commitId': 'bbb'
}
}
# This fails because there is no field named 'revision'
print(RevisionModel.parse_obj(data))
Is there a reasonably clever way to solve this within Pydantic, or do I have to resort to having fields for all the different types and implementing a method to get the revision based on 'revisionType'?