0Pricing
FastAPI Backend Development Bootcamp · Pelajaran

Mengelola Variabel Lingkungan dan Rahasia

Pelajari cara mengonfigurasi FastAPI dengan aman untuk berbagai lingkungan menggunakan variabel lingkungan dan pengelolaan rahasia.

Mengelola Variabel Lingkungan dan Rahasia adalah pelajaran FastAPI Backend Development Bootcamp gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar FastAPI Backend Development Bootcamp, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus FastAPI Backend Development Bootcamp mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

Why Externalize Configuration?

Hardcoding database URLs, API keys, or debug flags into your code is dangerous and inflexible.

The 12-factor app approach stores configuration in the environment, so the same image runs in dev, staging, and production with different settings.

Reading Environment Variables

Python reads variables via os.environ or os.getenv with a default.

import os

DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./dev.db")
DEBUG = os.getenv("DEBUG", "false").lower() == "true"

Pydantic Settings

FastAPI projects commonly use pydantic-settings to load and validate config into a typed object.

from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str
    secret_key: str
    debug: bool = False

Loading from a .env File

Configure the settings class to read a local .env file during development.

class Settings(BaseSettings):
    database_url: str
    secret_key: str

    class Config:
        env_file = ".env"

Caching the Settings Object

Use lru_cache so settings are parsed once and reused as a dependency.

from functools import lru_cache

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

Injecting Settings into Routes

Treat settings as a FastAPI dependency for clean access and easy testing.

from fastapi import Depends

@app.get("/info")
def info(settings: Settings = Depends(get_settings)):
    return {"debug": settings.debug}

Never Commit Secrets

Add .env to .gitignore. Committed secrets are extremely hard to fully remove from git history and may leak credentials.

# .gitignore
.env
*.pem
secrets/

Production Secret Stores

In production, prefer a managed secret store over plain files:

  • AWS Secrets Manager or Parameter Store
  • HashiCorp Vault
  • Docker or Kubernetes secrets

These inject secrets at runtime without writing them to disk in plain text.

Different Configs per Environment

Use a single variable like ENV to branch behavior, keeping all values in the environment.

ENV = os.getenv("ENV", "development")
if ENV == "production":
    LOG_LEVEL = "warning"
else:
    LOG_LEVEL = "debug"

Validating Required Variables

Pydantic settings raise a clear error at startup if a required variable is missing, failing fast instead of crashing later.

try:
    settings = Settings()
except Exception as e:
    print("Config error:", e)
    raise

Typed Lists and Nested Config

Settings can parse complex values too, like comma-separated origins into a list, keeping parsing logic out of your routes.

class Settings(BaseSettings):
    cors_origins: list[str] = []

# CORS_ORIGINS=https://a.com,https://b.com

Quick Check

Test your configuration knowledge.

Recap

You learned to manage configuration safely:

  • Read config from the environment, not source code
  • Use pydantic-settings for typed, validated config
  • Never commit .env; use a secret store in production

Solid config management keeps deployments portable and secure.

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Mengelola Variabel Lingkungan dan Rahasia” gratis?

Ya — teks lengkap “Mengelola Variabel Lingkungan dan Rahasia” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus FastAPI Backend Development Bootcamp, upgrade ke CoddyKit PRO. Kursus FastAPI Backend Development Bootcamp mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “Mengelola Variabel Lingkungan dan Rahasia”?

Pelajari cara mengonfigurasi FastAPI dengan aman untuk berbagai lingkungan menggunakan variabel lingkungan dan pengelolaan rahasia. Kamu berlatih FastAPI Backend Development Bootcamp dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai FastAPI Backend Development Bootcamp?

Tidak diperlukan pengalaman sebelumnya. FastAPI Backend Development Bootcamp di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.

Berapa lama pelajaran “Mengelola Variabel Lingkungan dan Rahasia” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran FastAPI Backend Development Bootcamp ini?

Ya. Setiap pelajaran FastAPI Backend Development Bootcamp menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Membuat Aplikasi FastAPI Menjadi Kontainer Docker
  2. Penerapan dengan Gunicorn dan Uvicorn
  3. Strategi Penerapan Cloud
  4. Mengelola Variabel Lingkungan dan Rahasia
← Kembali ke FastAPI Backend Development Bootcamp