Skip to content

Lesson 23 ยท Settings and Config

Secrets and Settings Patterns

Handle passwords and API keys safely with SecretStr, build settings once with a cached function, override them in tests and keep dev and production values apart.

Configuration often contains secrets: database passwords, API keys, signing keys. The danger is rarely an attacker reading your source; it is your own program printing the secret by accident into a log, an error report or a debug page. Pydantic gives you types that make this harder to do. This lesson covers secret types, a standard way to build settings once, how to replace settings in tests, and how to separate environments.

SecretStr and SecretBytes

SecretStr holds a string but hides it whenever it is printed, logged or serialized to JSON. The real text is available only through get_secret_value(), so reading it is a visible, deliberate act that you can search for in code review.

Python SecretStr hides the value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Printing the model, dumping it to a dictionary or to JSON all show **********. This protects against accidents, not against a determined reader of memory, so it complements proper secret storage, not replaces it. SecretBytes does the same for bytes, such as a signing key.

SecretStr hides a value in printed output and JSON, but model_dump(mode="python") still returns the SecretStr object, and anything that calls get_secret_value() gets the text. Never pass the raw value to a logger.

Secrets in a settings class

Combine SecretStr with BaseSettings so that a password read from the environment is hidden from the first moment. A repr of the whole settings object, which is exactly what ends up in a startup log, stays safe.

Python Secret fields in settings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The URL type PostgresDsn is a different story. It validates the shape and exposes the parts (host, user, path), but it does not hide the password inside it. If a URL carries a password, store it as SecretStr and parse it yourself, or print only host.

Build settings once with a cache

Creating Settings() reads the environment and files each time, which is wasteful and gives inconsistent values if something changes in between. The standard pattern is a function that builds the object once and returns the same one afterward, using functools.lru_cache:

Python
from functools import lru_cache

@lru_cache
def get_settings() -> Settings:
    return Settings()

Everything else calls get_settings(). In web frameworks this function is also the unit you can replace, which makes tests easy. The next example shows the cache and what clearing it does.

Python A cached get_settings()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Overriding settings in tests

A test should not depend on the developer's real environment. There are three good ways to give code test settings.

  1. Pass values directly. Settings(database_url="sqlite://", debug=True) ignores everything weaker than init arguments. Pass the object into the code under test instead of importing a global.
  2. Set the environment, then clear the cache. Change os.environ (a test framework's monkeypatch tool does this and restores it afterward) and call get_settings.cache_clear().
  3. Replace the provider. Web frameworks let you substitute get_settings with a function returning a test object; the FastAPI settings lesson shows this.
Python Test settings without a real environment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Passing the settings object as an argument is the simplest design: functions say what they need, and tests build exactly that.

Separating environments

A project usually runs in at least three places: development, tests and production. Keep the code identical and vary only the values.

  • Give every setting a safe default for local development, and no default for anything dangerous, such as a production database or a secret key. A required field fails fast when production forgets it.
  • Choose the dotenv file by an APP_ENV variable, for example env_file=(".env", f".env.{env}").
  • Keep real secrets in the platform's secret store and inject them as variables or mounted files. Only .env.example goes into git.
  • Add one environment field with a Literal["dev", "test", "prod"] type and validate production rules in a model validator, for instance "debug must be false in production". Custom Model Validators shows the technique.
Python Environment-specific safety rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does print(model) show for a SecretStr field?

    SecretStr masks the value in repr, str and JSON output. You get the real text only with get_secret_value().
  2. 2. Why wrap Settings() in an lru_cache function?

    Building once is faster and consistent, and the function becomes a single place to override in tests.
  3. 3. Which is the most direct way to give a function test settings?

    Init arguments have the highest priority and do not depend on any real environment.
  4. 4. Does PostgresDsn hide the password inside a URL?

    URL types expose their parts and print them in full. Keep a password you need to hide in a SecretStr.

Summary

  • SecretStr and SecretBytes mask values in printing, logging and JSON; call get_secret_value() deliberately.
  • Build settings once with a cached get_settings() and pass the object to code that needs it.
  • Test with explicit Settings(...) values, a changed environment plus cache_clear(), or a replaced provider.
  • Give dev-friendly defaults, but no default for production secrets, and add production rules in a model validator.

Next: Custom Field Validators