-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #344 from sanders41/pydantic-2
Make compatable with Pydantic 2
- Loading branch information
Showing
3 changed files
with
247 additions
and
139 deletions.
There are no files selected for viewing
This file contains 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 |
---|---|---|
@@ -1,18 +1,29 @@ | ||
try: | ||
from pydantic import BaseModel # type: ignore | ||
import pydantic # type: ignore | ||
except ImportError: | ||
raise ImportError("camel-converter must be installed with the pydantic extra to use this class") | ||
|
||
from camel_converter import to_camel | ||
|
||
|
||
class CamelBase(BaseModel): | ||
class CamelBase(pydantic.BaseModel): | ||
"""A Pydantic model that provides a base configuration for conveting between camel and snake case. | ||
If another Pydantic model inherit from this class it will get the ability to do this conversion | ||
between camel and snake case without having to add the configuration to the new model. | ||
""" | ||
|
||
class Config: | ||
alias_generator = to_camel | ||
allow_population_by_field_name = True | ||
try: | ||
# __version__ was added with Pydantic 2 so we know if this errors the version is < 2. | ||
# Still check the version as a fail safe incase __version__ gets added to verion 1. | ||
if int(pydantic.__version__[:1]) >= 2: # type: ignore[attr-defined] | ||
model_config = pydantic.ConfigDict(alias_generator=to_camel, populate_by_name=True) # type: ignore[attr-defined] | ||
else: # pragma: no cover | ||
# Raise an AttributeError to match the AttributeError on __version__ because in either | ||
# case we need to get to the same place. | ||
raise AttributeError | ||
except AttributeError: # pragma: no cover | ||
|
||
class Config: | ||
alias_generator = to_camel | ||
allow_population_by_field_name = True |
Oops, something went wrong.