Package: django-pydantic-settings
django-pydantic-settingsUse pydantic settings management to simplify configuration of Django settings.Very much a work in progress, but reads the standard DJANGO_SETTINGS_MODULE environment variable (defaulting to pydantic_settings.settings.PydanticSettings) to load a sub-class of pydantic_settings.Settings. All settings (that have been defined in pydantic_settings.Settings) can be overridden with environment variables. A special DatabaseSettings class is used to allow multiple databases to be configured simply with DSNs.As of django-pydantic-settings 0.6.0, Django 4.0 is now supported, but, as a result, support for Python 3.6 and 3.7 has been dropped. Python <3.8 can still be used with versions 0.5.0 and lower, and Django 3.2.x and lower; Python 3.6.0 requires django-pydantic-settings <0.4.0. Currently, django-pydantic-settings is tested on Python 3.8, 3.9, and 3.10, and Django 2.2, 3.0, 3.1, 3.2, and 4.0.Installation & SetupInstall django-pydantic-settings:pip install django-pydantic-settingsModify your Django project'smanage.pyfile to use django-pydantic-settings, it should look something like this:#!/usr/bin/env python"""Django's command-line utility for administrative tasks."""importsysfrompydantic_settingsimportSetUpdefmain():"""Run administrative tasks."""SetUp().configure()try:fromdjango.core.managementimportexecute_from_command_lineexceptImportErrorasexc:raiseImportError("Couldn't import Django. Are you sure it's installed and ""available on your PYTHONPATH environment variable? Did you ""forget to activate a virtual environment?")fromexcexecute_from_command_line(sys.argv)if__name__=="__main__":main()Yourwsgi.pyand/orasgi.pyfiles will need to be modified similarly, and look something like this:fromdjango.core.wsgiimportget_wsgi_applicationfrompydantic_settingsimportSetUpSetUp().configure()application=get_wsgi_application()TheSetUpclass will automatically look for the standardDJANGO_SETTINGS_MODULEenvironment variable, read it, confirm that it points to an existing Python module, and load that module. YourDJANGO_SETTINGS_MODULEvariable should point to apydantic_settings.settings.PydanticSettingssub-class (though technically any Python class that defines adict()method which returns a Python dictionary of key/value pairs matching the required Django settings will work). Calling theconfigure()method will then use the specified module to configure your project's Django settings.If your project uses a package to specify multiple different settings classes, simply setDJANGO_SETTINGS_MODULEto be the full path to the desired settings class. For example, given the following directory structure:my_project/
├─ settings/
│  ├─ __init__.py
│  ├─ base.py
│  ├─ local.py
│  ├─ production.py
├─ my_app/To use a settings class calledMyLocalinlocal.pyyou would set yourDJANGO_SETTINGS_MODULEtomy_project.settings.local.MyLocal.Required settingsThere are no settings that must be configured in order to use Django with django-pydantic-settings. All of the possible settings defined by Django (Settings Reference) are configured in thepydantic_settings.settings.PydanticSettingsclass, using their normal default values provided by Django, or a reasonable calculated value. Settings worth thinking about areROOT_URLCONFandWSGI_APPLICATION, which, unless otherwise specified, are calculated based on yourDJANGO_SETTINGS_MODULEassuming that you're using the default Django project layout a provided bydjango-admin.py startproject. So, for example, if yourDJANGO_SETINGS_MODULEis set tomy_awesome_project.settings.PydanticSettingsSubclass, thenROOT_URLCONFandWSGI_APPLICATIONwill be set tomy_awesome_project.urlsandmy_awesome_project.wsgirespectively. This default behavior can be overridden by simply specifyingROOT_URLCONF:str = 'the_actual_urlconf'andWSGI_APPLICATION:str = 'the_actual_wsgi_file.application'in yourPydanticSettingssub-class. Alternatively, rather than individually settings theROOT_URLCONFandWSGI_APPLICATIONsettings, you can setBASE_DIR, and that will be used instead ofDJANGO_SETTINGS_MODULE.The other setting worth thinking about isSECRET_KEY. By default,SECRET_KEYis automatically generated using Django's ownget_random_secret_key()function. This will work just fine, though as it will be re-calculated every time yourPydanticSettingssub-class is instantiated, you should set this to somethign static if you're using Django's authentication and don't want to lose your session every time the server is restarted.Database configurationThe default database configuration can be configured by an environment variable namedDATABASE_URL, containing a DSN (Data Source Name) string.Google Cloud SQL database connections from within Google Cloud Run are supported; theDatabaseDsntype will detect and automatically escape DSN strings of the formpostgres://username:password@/cloudsql/project:region:instance/databaseso that they can be properly handled.Alternatively you can set all your databases at once, by using theDATABASESsetting (either in aPydanticSettingssub-class or via theDJANGO_DATABASESenvironment variable:defMySettings(PydanticSettings):DATABASES={"default":"sqlite:///db.sqlite3"}# type: ignoreIt is also possible to configure additional database connections with environment variables in the same way as the defaultDATABASE_URLconfiguration by using aFieldthat has aconfigure_databaseargument that points to the database alias in theDATABASESdictionary.frompydantic_settingsimportPydanticSettingsfrompydantic_settings.databaseimportDatabaseDsndefMySettings(PydanticSettings):secondary_database_dsn:Optional[DatabaseDsn]=Field(env="SECONDARY_DATABASE_URL",configure_database="secondary")For example, thesettings_test/database_settings.pyfile is has a settings subclass configured like this and outputs the changes to theDATABASESsetting when run directly:❯ DATABASE_URL=postgres://username:password@/cloudsql/project:region:instance/database SECONDARY_DATABASE_URL=sqlite:///foo python settings_test/database_settings.py
{'default': {'ENGINE': 'django.db.backends.postgresql',
             'HOST': '/cloudsql/project:region:instance',
             'NAME': 'database',
             'PASSWORD': 'password',
             'USER': 'username'},
 'secondary': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'foo'}}Sentry configurationdjango-pydantic-settings provides built-in functionality for configuring your Django project to useSentry. The simplest way to use this is to inherit frompydantic_settings.sentry.SentrySettingsrather thanpydantic_settings.settings.PydanticSettings. This adds the settingSENTRY_DSN, which uses thepydantic_settings.sentry.SentryDsntype. This will automatically be set according to theDJANGO_SENTRY_DSNenvironment variable, and expects a Sentry DSN (obviously). It validates that the provided DSN is a valid URL, and then automatically initializes the Sentry SDK using the built-in DjangoIntegration. Using this functionality requiredsentry-sdkto be installed, which will be included automatically if you installdjango-pydantic-settings[sentry].