liveBook · Manning

Os.getenv

As explained in Build Financial Software with Generative AI (From Scratch)

os.getenv is a Python standard-library function that retrieves a named environment variable and can return a fallback when it is absent.

os.getenv retrieves a named environment variable from Python, helping move database credentials out of application code and into deployment configuration. section 3.7

import os
…
POSTGRES_USER = os.getenv("POSTGRES_USER")
POSTGRES_PASSWORD = os.getenv("POSTGRES_PASSWORD")
…
DATABASE_URL = f"dbname={POSTGRES_USER} user={POSTGRES_USER}
➥ password={POSTGRES_PASSWORD} host=postgres port=5432"

The API imports os, reads PostgreSQL credentials with os.getenv, and builds a database connection string from the returned values. section 3.7

Optional fallback

os.getenv("POSTGRES_USER", "postgres") returns the configured value when present and "postgres" when the variable is absent. Omitting the fallback can expose configuration mistakes instead of allowing an accidental connection. section 3.7

A practical configuration flow:

  • Define POSTGRES_USER and POSTGRES_PASSWORD in an environment file. section 3.7
  • Load that file into Docker Compose services with env_file. section 3.7
  • Read the variables in Python and use them in the PostgreSQL connection string. section 3.7

How Build Financial Software with Generative AI (From Scratch) covers it

How deep it goes
Defines retrieval and fallback behavior, then demonstrates integration with environment files and a database connection string.
Examples
Uses POSTGRES_USER, POSTGRES_PASSWORD, an environment file, and a PostgreSQL DATABASE_URL.
What it assumes
Assumes basic Python imports and Docker Compose configuration while demonstrating environment-based credential setup.
What you can do after
Operate/configure a containerized API by reading deployment-provided database settings and choosing whether missing values receive fallbacks.
How it connects
Connects environment variables, Docker Compose, environment files, and PostgreSQL connection strings.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Financial Software with Generative AI (From Scratch). The section links point to the parts of the book it draws on.