Skip to content

prefect.settings.models.root

Settings

Bases: PrefectBaseSettings

Settings for Prefect using Pydantic settings.

See https://docs.pydantic.dev/latest/concepts/pydantic_settings

Source code in src/prefect/settings/models/root.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
class Settings(PrefectBaseSettings):
    """
    Settings for Prefect using Pydantic settings.

    See https://docs.pydantic.dev/latest/concepts/pydantic_settings
    """

    model_config = _build_settings_config()

    home: Annotated[Path, BeforeValidator(lambda x: Path(x).expanduser())] = Field(
        default=Path("~") / ".prefect",
        description="The path to the Prefect home directory. Defaults to ~/.prefect",
    )

    profiles_path: Optional[Path] = Field(
        default=None,
        description="The path to a profiles configuration file.",
    )

    debug_mode: bool = Field(
        default=False,
        description="If True, enables debug mode which may provide additional logging and debugging features.",
    )

    api: APISettings = Field(
        default_factory=APISettings,
        description="Settings for interacting with the Prefect API",
    )

    cli: CLISettings = Field(
        default_factory=CLISettings,
        description="Settings for controlling CLI behavior",
    )

    client: ClientSettings = Field(
        default_factory=ClientSettings,
        description="Settings for for controlling API client behavior",
    )

    cloud: CloudSettings = Field(
        default_factory=CloudSettings,
        description="Settings for interacting with Prefect Cloud",
    )

    deployments: DeploymentsSettings = Field(
        default_factory=DeploymentsSettings,
        description="Settings for configuring deployments defaults",
    )

    experiments: ExperimentsSettings = Field(
        default_factory=ExperimentsSettings,
        description="Settings for controlling experimental features",
    )

    flows: FlowsSettings = Field(
        default_factory=FlowsSettings,
        description="Settings for controlling flow behavior",
    )

    internal: InternalSettings = Field(
        default_factory=InternalSettings,
        description="Settings for internal Prefect machinery",
    )

    logging: LoggingSettings = Field(
        default_factory=LoggingSettings,
        description="Settings for controlling logging behavior",
    )

    results: ResultsSettings = Field(
        default_factory=ResultsSettings,
        description="Settings for controlling result storage behavior",
    )

    runner: RunnerSettings = Field(
        default_factory=RunnerSettings,
        description="Settings for controlling runner behavior",
    )

    server: ServerSettings = Field(
        default_factory=ServerSettings,
        description="Settings for controlling server behavior",
    )

    tasks: TasksSettings = Field(
        default_factory=TasksSettings,
        description="Settings for controlling task behavior",
    )

    testing: TestingSettings = Field(
        default_factory=TestingSettings,
        description="Settings used during testing",
    )

    worker: WorkerSettings = Field(
        default_factory=WorkerSettings,
        description="Settings for controlling worker behavior",
    )

    ui_url: Optional[str] = Field(
        default=None,
        description="The URL of the Prefect UI. If not set, the client will attempt to infer it.",
    )

    silence_api_url_misconfiguration: bool = Field(
        default=False,
        description="""
        If `True`, disable the warning when a user accidentally misconfigure its `PREFECT_API_URL`
        Sometimes when a user manually set `PREFECT_API_URL` to a custom url,reverse-proxy for example,
        we would like to silence this warning so we will set it to `FALSE`.
        """,
    )

    ###########################################################################
    # allow deprecated access to PREFECT_SOME_SETTING_NAME

    def __getattribute__(self, name: str) -> Any:
        from prefect.settings.legacy import _env_var_to_accessor

        if name.startswith("PREFECT_"):
            accessor = _env_var_to_accessor(name)
            warnings.warn(
                f"Accessing `Settings().{name}` is deprecated. Use `Settings().{accessor}` instead.",
                DeprecationWarning,
                stacklevel=2,
            )
            path = accessor.split(".")
            value = super().__getattribute__(path[0])
            for key in path[1:]:
                value = getattr(value, key)
            return value
        return super().__getattribute__(name)

    ###########################################################################

    @model_validator(mode="after")
    def post_hoc_settings(self) -> Self:
        """refactor on resolution of https://github.com/pydantic/pydantic/issues/9789

        we should not be modifying __pydantic_fields_set__ directly, but until we can
        define dependencies between defaults in a first-class way, we need clean up
        post-hoc default assignments to keep set/unset fields correct after instantiation.
        """
        if self.ui_url is None:
            self.ui_url = _default_ui_url(self)
            self.__pydantic_fields_set__.remove("ui_url")
        if self.server.ui.api_url is None:
            if self.api.url:
                self.server.ui.api_url = self.api.url
                self.server.ui.__pydantic_fields_set__.remove("api_url")
            else:
                self.server.ui.api_url = (
                    f"http://{self.server.api.host}:{self.server.api.port}/api"
                )
                self.server.ui.__pydantic_fields_set__.remove("api_url")
        if self.profiles_path is None or "PREFECT_HOME" in str(self.profiles_path):
            self.profiles_path = Path(f"{self.home}/profiles.toml")
            self.__pydantic_fields_set__.remove("profiles_path")
        if self.results.local_storage_path is None:
            self.results.local_storage_path = Path(f"{self.home}/storage")
            self.results.__pydantic_fields_set__.remove("local_storage_path")
        if self.server.memo_store_path is None:
            self.server.memo_store_path = Path(f"{self.home}/memo_store.toml")
            self.server.__pydantic_fields_set__.remove("memo_store_path")
        if self.debug_mode or self.testing.test_mode:
            self.logging.level = "DEBUG"
            self.internal.logging_level = "DEBUG"
            self.logging.__pydantic_fields_set__.remove("level")
            self.internal.__pydantic_fields_set__.remove("logging_level")

        if self.logging.config_path is None:
            self.logging.config_path = Path(f"{self.home}/logging.yml")
            self.logging.__pydantic_fields_set__.remove("config_path")
        # Set default database connection URL if not provided
        if self.server.database.connection_url is None:
            self.server.database.connection_url = _default_database_connection_url(self)
            self.server.database.__pydantic_fields_set__.remove("connection_url")
        db_url = (
            self.server.database.connection_url.get_secret_value()
            if isinstance(self.server.database.connection_url, SecretStr)
            else self.server.database.connection_url
        )
        if (
            "PREFECT_API_DATABASE_PASSWORD" in db_url
            or "PREFECT_SERVER_DATABASE_PASSWORD" in db_url
        ):
            if self.server.database.password is None:
                raise ValueError(
                    "database password is None - please set PREFECT_SERVER_DATABASE_PASSWORD"
                )
            db_url = db_url.replace(
                "${PREFECT_API_DATABASE_PASSWORD}",
                self.server.database.password.get_secret_value()
                if self.server.database.password
                else "",
            )
            db_url = db_url.replace(
                "${PREFECT_SERVER_DATABASE_PASSWORD}",
                self.server.database.password.get_secret_value()
                if self.server.database.password
                else "",
            )
            self.server.database.connection_url = SecretStr(db_url)
            self.server.database.__pydantic_fields_set__.remove("connection_url")
        return self

    @model_validator(mode="after")
    def emit_warnings(self) -> Self:
        """More post-hoc validation of settings, including warnings for misconfigurations."""
        if not self.silence_api_url_misconfiguration:
            _warn_on_misconfigured_api_url(self)
        return self

    ##########################################################################
    # Settings methods

    def copy_with_update(
        self: Self,
        updates: Optional[Mapping["Setting", Any]] = None,
        set_defaults: Optional[Mapping["Setting", Any]] = None,
        restore_defaults: Optional[Iterable["Setting"]] = None,
    ) -> Self:
        """
        Create a new Settings object with validation.

        Arguments:
            updates: A mapping of settings to new values. Existing values for the
                given settings will be overridden.
            set_defaults: A mapping of settings to new default values. Existing values for
                the given settings will only be overridden if they were not set.
            restore_defaults: An iterable of settings to restore to their default values.

        Returns:
            A new Settings object.
        """
        # To restore defaults, we need to resolve the setting path and then
        # set the default value on the new settings object. When restoring
        # defaults, all settings sources will be ignored.
        restore_defaults_obj = {}
        for r in restore_defaults or []:
            path = r.accessor.split(".")
            model = self
            for key in path[:-1]:
                model = model.model_fields[key].annotation
                assert model is not None, f"Invalid setting path: {r.accessor}"

            model_field = model.model_fields[path[-1]]
            assert model is not None, f"Invalid setting path: {r.accessor}"
            if hasattr(model_field, "default"):
                default = model_field.default
            elif (
                hasattr(model_field, "default_factory") and model_field.default_factory
            ):
                default = model_field.default_factory()
            else:
                raise ValueError(f"No default value for setting: {r.accessor}")
            set_in_dict(
                restore_defaults_obj,
                r.accessor,
                default,
            )
        updates = updates or {}
        set_defaults = set_defaults or {}

        set_defaults_obj = {}
        for setting, value in set_defaults.items():
            set_in_dict(set_defaults_obj, setting.accessor, value)

        updates_obj = {}
        for setting, value in updates.items():
            set_in_dict(updates_obj, setting.accessor, value)

        new_settings = self.__class__.model_validate(
            deep_merge_dicts(
                set_defaults_obj,
                self.model_dump(exclude_unset=True),
                restore_defaults_obj,
                updates_obj,
            )
        )
        return new_settings

    def hash_key(self) -> str:
        """
        Return a hash key for the settings object.  This is needed since some
        settings may be unhashable, like lists.
        """
        env_variables = self.to_environment_variables()
        return str(hash(tuple((key, value) for key, value in env_variables.items())))

copy_with_update(updates=None, set_defaults=None, restore_defaults=None)

Create a new Settings object with validation.

Parameters:

Name Type Description Default
updates Optional[Mapping[Setting, Any]]

A mapping of settings to new values. Existing values for the given settings will be overridden.

None
set_defaults Optional[Mapping[Setting, Any]]

A mapping of settings to new default values. Existing values for the given settings will only be overridden if they were not set.

None
restore_defaults Optional[Iterable[Setting]]

An iterable of settings to restore to their default values.

None

Returns:

Type Description
Self

A new Settings object.

Source code in src/prefect/settings/models/root.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def copy_with_update(
    self: Self,
    updates: Optional[Mapping["Setting", Any]] = None,
    set_defaults: Optional[Mapping["Setting", Any]] = None,
    restore_defaults: Optional[Iterable["Setting"]] = None,
) -> Self:
    """
    Create a new Settings object with validation.

    Arguments:
        updates: A mapping of settings to new values. Existing values for the
            given settings will be overridden.
        set_defaults: A mapping of settings to new default values. Existing values for
            the given settings will only be overridden if they were not set.
        restore_defaults: An iterable of settings to restore to their default values.

    Returns:
        A new Settings object.
    """
    # To restore defaults, we need to resolve the setting path and then
    # set the default value on the new settings object. When restoring
    # defaults, all settings sources will be ignored.
    restore_defaults_obj = {}
    for r in restore_defaults or []:
        path = r.accessor.split(".")
        model = self
        for key in path[:-1]:
            model = model.model_fields[key].annotation
            assert model is not None, f"Invalid setting path: {r.accessor}"

        model_field = model.model_fields[path[-1]]
        assert model is not None, f"Invalid setting path: {r.accessor}"
        if hasattr(model_field, "default"):
            default = model_field.default
        elif (
            hasattr(model_field, "default_factory") and model_field.default_factory
        ):
            default = model_field.default_factory()
        else:
            raise ValueError(f"No default value for setting: {r.accessor}")
        set_in_dict(
            restore_defaults_obj,
            r.accessor,
            default,
        )
    updates = updates or {}
    set_defaults = set_defaults or {}

    set_defaults_obj = {}
    for setting, value in set_defaults.items():
        set_in_dict(set_defaults_obj, setting.accessor, value)

    updates_obj = {}
    for setting, value in updates.items():
        set_in_dict(updates_obj, setting.accessor, value)

    new_settings = self.__class__.model_validate(
        deep_merge_dicts(
            set_defaults_obj,
            self.model_dump(exclude_unset=True),
            restore_defaults_obj,
            updates_obj,
        )
    )
    return new_settings

emit_warnings()

More post-hoc validation of settings, including warnings for misconfigurations.

Source code in src/prefect/settings/models/root.py
245
246
247
248
249
250
@model_validator(mode="after")
def emit_warnings(self) -> Self:
    """More post-hoc validation of settings, including warnings for misconfigurations."""
    if not self.silence_api_url_misconfiguration:
        _warn_on_misconfigured_api_url(self)
    return self

hash_key()

Return a hash key for the settings object. This is needed since some settings may be unhashable, like lists.

Source code in src/prefect/settings/models/root.py
321
322
323
324
325
326
327
def hash_key(self) -> str:
    """
    Return a hash key for the settings object.  This is needed since some
    settings may be unhashable, like lists.
    """
    env_variables = self.to_environment_variables()
    return str(hash(tuple((key, value) for key, value in env_variables.items())))

post_hoc_settings()

refactor on resolution of https://github.com/pydantic/pydantic/issues/9789

we should not be modifying pydantic_fields_set directly, but until we can define dependencies between defaults in a first-class way, we need clean up post-hoc default assignments to keep set/unset fields correct after instantiation.

Source code in src/prefect/settings/models/root.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
@model_validator(mode="after")
def post_hoc_settings(self) -> Self:
    """refactor on resolution of https://github.com/pydantic/pydantic/issues/9789

    we should not be modifying __pydantic_fields_set__ directly, but until we can
    define dependencies between defaults in a first-class way, we need clean up
    post-hoc default assignments to keep set/unset fields correct after instantiation.
    """
    if self.ui_url is None:
        self.ui_url = _default_ui_url(self)
        self.__pydantic_fields_set__.remove("ui_url")
    if self.server.ui.api_url is None:
        if self.api.url:
            self.server.ui.api_url = self.api.url
            self.server.ui.__pydantic_fields_set__.remove("api_url")
        else:
            self.server.ui.api_url = (
                f"http://{self.server.api.host}:{self.server.api.port}/api"
            )
            self.server.ui.__pydantic_fields_set__.remove("api_url")
    if self.profiles_path is None or "PREFECT_HOME" in str(self.profiles_path):
        self.profiles_path = Path(f"{self.home}/profiles.toml")
        self.__pydantic_fields_set__.remove("profiles_path")
    if self.results.local_storage_path is None:
        self.results.local_storage_path = Path(f"{self.home}/storage")
        self.results.__pydantic_fields_set__.remove("local_storage_path")
    if self.server.memo_store_path is None:
        self.server.memo_store_path = Path(f"{self.home}/memo_store.toml")
        self.server.__pydantic_fields_set__.remove("memo_store_path")
    if self.debug_mode or self.testing.test_mode:
        self.logging.level = "DEBUG"
        self.internal.logging_level = "DEBUG"
        self.logging.__pydantic_fields_set__.remove("level")
        self.internal.__pydantic_fields_set__.remove("logging_level")

    if self.logging.config_path is None:
        self.logging.config_path = Path(f"{self.home}/logging.yml")
        self.logging.__pydantic_fields_set__.remove("config_path")
    # Set default database connection URL if not provided
    if self.server.database.connection_url is None:
        self.server.database.connection_url = _default_database_connection_url(self)
        self.server.database.__pydantic_fields_set__.remove("connection_url")
    db_url = (
        self.server.database.connection_url.get_secret_value()
        if isinstance(self.server.database.connection_url, SecretStr)
        else self.server.database.connection_url
    )
    if (
        "PREFECT_API_DATABASE_PASSWORD" in db_url
        or "PREFECT_SERVER_DATABASE_PASSWORD" in db_url
    ):
        if self.server.database.password is None:
            raise ValueError(
                "database password is None - please set PREFECT_SERVER_DATABASE_PASSWORD"
            )
        db_url = db_url.replace(
            "${PREFECT_API_DATABASE_PASSWORD}",
            self.server.database.password.get_secret_value()
            if self.server.database.password
            else "",
        )
        db_url = db_url.replace(
            "${PREFECT_SERVER_DATABASE_PASSWORD}",
            self.server.database.password.get_secret_value()
            if self.server.database.password
            else "",
        )
        self.server.database.connection_url = SecretStr(db_url)
        self.server.database.__pydantic_fields_set__.remove("connection_url")
    return self