我定义了一个Pydantic模式,它接受未知字段,如下所示:
from stringcase import camelcase
from pydantic import BaseModel as pydanticBaseModel
class BaseModel(pydanticBaseModel):
MyName: str = Field(..., alias="myName")
class Config:
allow_population_by_field_name = True
extra = Extra.allow
alias_generator = camelcase
是否有可能通过使用alias_generator
或任何其他方式将未知传入属性转换为camelCase ?目前它不识别额外的
我想要像下面这样:
inp = {
"MyName": "Name",
"Address": "bla bla",
"Post": "post"
}
BaseModel(**inp).dict(by_alias=True)
已知和未知字段的输出应该是camelCase格式:
{
"myName": "Name",
"address": "bla bla",
"post": "post"
}
from typing import *
from pydantic import Field, BaseModel, Extra
from caseconverter import camelcase
class MyBase(BaseModel):
class Config:
allow_population_by_field_name = True
extra = Extra.allow
validate_assignment = True
def get_extra_fields(self):
return {field: camelcase(field) for field in set(self.__fields_set__ - set(self.__fields__.keys()))}
def camelize(self, to_camel=False):
extra_fields = self.get_extra_fields()
for extra_field, camelcase_alias in extra_fields.items():
current, target = (extra_field, camelcase_alias) if to_camel else (camelcase_alias, extra_field)
if not hasattr(self, target):
value = getattr(self, current, None)
setattr(self, target, value)
delattr(self, current)
def dict(self, **kwargs):
self.camelize(to_camel=kwargs.get("by_alias", False))
return super().dict(**kwargs)
class Child(MyBase):
name: str = Field(None, alias="namE")
age: int = Field(None, alias="agE")
class Parent(MyBase):
mother: str = Field(None, alias="motheR")
father: str = Field(None, alias="fatheR")
children: List[Child] = Field(None, alias="childreN")
# my raw data for testing
data = {
"mother": "bla",
"father": "blabla",
"Out_Sider": "blabla",
"children": [
{
"name": "blabla",
"age": 30,
"SurName": "blabla",
},
{
"name": "blabla",
"age": 28,
"SurName": "blabla",
}
]
}
parent = Parent(**data)
parent.dict(by_alias=False)
'''Output
{'mother': 'bla',
'father': 'blabla',
'children': [{'name': 'blabla', 'age': 23, 'SurName':'blabla'},
{'name': 'blabla', 'age': 34, 'SurName': 'blabla'}],
'Out_Sider': 'blabla'}
'''
parent.dict(by_alias=True)
'''Output
{'motheR': 'bla',
'fatheR': 'blabla',
'childreN': [{'namE': 'blabla', 'agE': 30, 'surName': 'blabla'},
{'namE': 'blabla', 'agE': 28, 'surName': 'blabla'}],
'outSider': 'blabla'}
'''