IC Improve Code Recipes

Recipe 6.3 · Python

Environments Without web.config Transforms

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Each environment needs different settings: a local database for developers, a test server for QA, production values in production. The legacy approach was Web.Release.config transforms applied at publish time, which meant a different build per environment, and production settings that lived in the repository. Worse, when something misbehaves you can't tell which file a value came from.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

XML
<!-- Not this: environment values baked in at build time. -->
<appSettings>
  <add key="ApiUrl" value="https://api.example.com"
       xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
  <add key="SmtpPassword" value="Pr0dP@ss!"
       xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
</appSettings>

The improved recipe

Build once, configure per environment at run time. The environment name selects an optional appsettings.{Environment}.json, and environment variables or a vault supply the secrets. Log a short summary at startup so you can always see what the app loaded.

Text
appsettings.json               defaults shared by every environment
appsettings.Development.json   local machine values, no secrets
appsettings.Staging.json       test server values, no secrets
appsettings.Production.json    production values, no secrets

Usage in Program.cs:

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Logging the environment and configuration sources, and finding a key's source (p128_r6_3_configuration_source_diagnostics.py)
"""Logging the environment and configuration sources, and finding a key's source

Source: ImproveCode, Chapter 6, Recipe 6.3 "Environments Without web.config Transforms"
Section: The improved recipe
Book page: 128-129  -- original C# listing
Converted from C# to Python.
IConfigurationRoot.Providers is modelled as an ordered list of named sources
(ConfigSource: a name plus its flattened key/value dict); logging replaces ILogger.
Values are never logged.
"""

from __future__ import annotations

import logging
from dataclasses import dataclass, field
from typing import Mapping


@dataclass(frozen=True)
class ConfigSource:
    name: str
    values: Mapping[str, str] = field(default_factory=dict)

    def try_get(self, key: str) -> bool:
        return key in self.values

    def __str__(self) -> str:
        return self.name


@dataclass(frozen=True)
class HostEnvironment:
    application_name: str
    environment_name: str
    content_root_path: str


class ConfigurationDiagnostics:
    @staticmethod
    def log_summary(
        providers: list[ConfigSource] | None,
        environment: HostEnvironment,
        logger: logging.Logger,
    ) -> None:
        """Logs the environment and configuration sources, never values."""
        logger.info(
            "Starting %s in %s from %s",
            environment.application_name,
            environment.environment_name,
            environment.content_root_path)

        if providers is None:
            return

        for provider in providers:
            logger.info("Configuration source: %s", provider)

    @staticmethod
    def find_source(providers: list[ConfigSource], key: str) -> str | None:
        """Returns the source that supplies a key. The last
        provider that has the key wins."""
        for provider in reversed(providers):
            if provider.try_get(key):
                return str(provider)
        return None

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Logging the configuration summary once the app is built (p129_r6_3_log_config_summary_at_startup.py)
"""Logging the configuration summary once the app is built

Source: ImproveCode, Chapter 6, Recipe 6.3 "Environments Without web.config Transforms"
Section: The improved recipe
Book page: 129  -- original C# listing
Converted from C# to Python.
ConfigurationDiagnostics is from p128_r6_3_configuration_source_diagnostics.py; a
FastAPI startup (lifespan) hook would be the natural place to call this.
"""

from __future__ import annotations

import logging
from typing import Any


def on_startup(configuration_diagnostics: Any, providers: Any, environment: Any) -> None:
    configuration_diagnostics.log_summary(
        providers, environment, logging.getLogger("app"))

How it works

The host reads the environment name from ASPNETCORE_ENVIRONMENT (web apps) or DOTNET_ENVIRONMENT (any host). If neither is set, the environment is Production, which is the safe default: a forgotten variable on a server never turns on developer exception pages.

WebApplication.CreateBuilder loads sources in this order, later ones winning:

  1. appsettings.json
  2. appsettings.{Environment}.json
  3. User secrets (Development only)
  4. Environment variables
  5. Command-line arguments

The same build output runs everywhere. Moving a release from staging to production changes the environment variable, not the binaries. The environment JSON files carry only the values that differ and contain no secrets, so they are safe to commit.

The startup summary logs lines such as JsonConfigurationProvider for 'appsettings.Production.json' (Optional). When someone asks "why is production calling the test API?" the answer is usually that the environment name was wrong or the file wasn't deployed, and the first ten lines of the log now say so. FindSource answers the more specific question of which source won for one key, which is handy in a diagnostics endpoint protected for administrators.

Variations and pitfalls

  • In IIS, set the environment with an <environmentVariable> element under <aspNetCore> in web.config, or on the application pool. Publish profiles can write it for you.
  • You can use any environment name: IsEnvironment("UAT") works, and so does appsettings.UAT.json. Keep the list short.
  • root.GetDebugView() prints every key, its value and its source. It's great on a developer machine and a disaster in a production log, because it prints secrets too.
  • Don't branch on the environment throughout the code (if (env.IsProduction()) ...). Put the difference in configuration and keep one code path.
  • Remember that reloadOnChange is on by default for the JSON files in a host. Editing appsettings.json on a live server changes IOptionsMonitor values within seconds, which is useful for log levels and surprising for anything else.