python-dependency-injector icon indicating copy to clipboard operation
python-dependency-injector copied to clipboard

Support pydantic v2 BaseSettings

Open arianamiri opened this issue 1 year ago • 5 comments

In pydantic 2.0+ the BaseSettings class has been moved into a optional package, pydantic-settings. The configuration provider's from_pydantic method expect to find it in the pydantic package:

https://github.com/ets-labs/python-dependency-injector/blob/master/src/dependency_injector/providers.pyx#L1806-L1816

This results in an error like:

    container.config.from_pydantic(settings)
src/dependency_injector/providers.pyx:2381: in dependency_injector.providers.Configuration.from_pydantic
    ???
.venv/lib/python3.11/site-packages/pydantic/__init__.py:218: in __getattr__
    return _getattr_migration(attr_name)
.venv/lib/python3.11/site-packages/pydantic/_migration.py:294: in wrapper
    raise PydanticImportError(
E   pydantic.errors.PydanticImportError: `BaseSettings` has been moved to the `pydantic-settings` package. See https://docs.pydantic.dev/2.4/migration/#basesettings-has-moved-to-pydantic-settings for more details.

Furthermore, the BaseModel.dict method used in the last line of this method is deprecated and has been replaced by BaseModel.model_dump. The method still exists but emits deprecation warnings when accessed.

arianamiri avatar Oct 25 '23 18:10 arianamiri

I created PR covering this issue.

tsaryapkin avatar Nov 26 '23 10:11 tsaryapkin

A work around that I used for this would be:

config = providers.Configuration() 
json_config = Settings().model_dump(mode='json') 
config.from_dict(json_config)

cdonate avatar Jan 10 '24 19:01 cdonate

The same issue

Temporary solved with:

config = providers.Configuration()
config.from_dict(AppSecrets().dict())

pow3rpi avatar Jun 28 '24 23:06 pow3rpi

FYI for anyone else who lands here: @cdonate's workaround is compatible with Pydantic v2.

While @pow3rpi's workaround is technically compatible with Pydantic v2, the .dict() and .json() model serialization methods are marked as deprecated in v2 and will eventually be removed in favor of .model_dump() and .model_dump_json().

bmcandr avatar Jul 02 '24 16:07 bmcandr

@bmcandr Good point! Thanks.

pow3rpi avatar Jul 02 '24 22:07 pow3rpi