您應該如何使用環境變量配置Python應用程序?
使用環境變量配置Python應用,首先在開發時通過python-dotenv加載.env文件中的變量,1. 使用os.getenv()並提供默認值避免錯誤,2. 按環境(如開發、生產)結構化配置,3. 生產環境中通過部署平台設置環境變量,4. 始終將環境變量作為配置的唯一來源,確保敏感信息不進入代碼或版本控制,應用行為僅由環境決定。
You should use environment variables to configure a Python application by loading them at runtime to keep configuration separate from code, especially for settings that vary between environments (like development, staging, and production). This approach follows the twelve-factor app methodology and helps keep sensitive data like API keys and database URLs out of version control.

Use a .env
file during development
During development, it's common to use a .env
file to store environment variables locally. This file is listed in .gitignore
so it's not committed to version control. You can use the python-dotenv
package to load these variables:
pip install python-dotenv
Create a .env
file in your project root:

DATABASE_URL=postgresql://user:pass@localhost:5432/mydb SECRET_KEY=your-secret-key DEBUG=True
Then load it in your Python code:
from dotenv import load_dotenv import os load_dotenv() # Load environment variables from .env database_url = os.getenv("DATABASE_URL") secret_key = os.getenv("SECRET_KEY") debug = os.getenv("DEBUG", "False").lower() == "true"
Note : Never commit
.env
files with secrets to Git. Use a.env.example
file to show required variables (without values) for onboarding new developers.
Access variables using os.getenv()
with defaults
Always use os.getenv()
instead of os.environ[]
to avoid KeyError
exceptions. Provide sensible defaults when possible:
import os port = int(os.getenv("PORT", 8000)) debug = os.getenv("DEBUG", "False").lower() == "true" allowed_hosts = os.getenv("ALLOWED_HOSTS", "localhost,127.0.0.1").split(",")
This makes your app more resilient and easier to run in different environments without requiring every variable to be set.
Use environment-specific configuration
Structure your configuration based on the current environment. For example:
import os env = os.getenv("ENV", "development") if env == "production": database_url = os.getenv("DATABASE_URL") debug = False elif env == "staging": database_url = os.getenv("DATABASE_URL") debug = True else: database_url = "sqlite:///dev.db" debug = True
Alternatively, use a config class pattern:
class Config: SECRET_KEY = os.getenv("SECRET_KEY", "dev-secret") DATABASE_URL = os.getenv("DATABASE_URL") class DevelopmentConfig(Config): DEBUG = True class ProductionConfig(Config): DEBUG = False config = { "development": DevelopmentConfig, "production": ProductionConfig }[os.getenv("ENV", "development")]
Set environment variables in production
In production, don't rely on .env
files. Instead, set environment variables through your deployment platform:
- Docker : Use
environment
indocker-compose.yml
orENV
in Dockerfile - Kubernetes : Use
env
in pod spec or ConfigMaps/Secrets - Cloud platforms (eg, Heroku, AWS, GCP) : Use platform-specific config commands or UI
- System level : Set in shell (eg,
export DATABASE_URL=...
) or systemd service files
For example, on Heroku:
heroku config:set DATABASE_URL=your-prod-db-url
Or in Docker:
# docker-compose.yml environment: - DATABASE_URL=postgresql://... - DEBUG=False
Summary
- Use
python-dotenv
and.env
files only for development - Always use
os.getenv()
with fallbacks to avoid crashes - Keep secrets out of code and version control
- Structure config by environment
- Set real environment variables in production via deployment tools
Basically, treat environment variables as the single source of truth for configuration—your app should behave differently based solely on its environment, not on hardcoded values.
以上是您應該如何使用環境變量配置Python應用程序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

安裝pyodbc:使用pipinstallpyodbc命令安裝庫;2.連接SQLServer:通過pyodbc.connect()方法,使用包含DRIVER、SERVER、DATABASE、UID/PWD或Trusted_Connection的連接字符串,分別支持SQL身份驗證或Windows身份驗證;3.查看已安裝驅動:運行pyodbc.drivers()並篩選含'SQLServer'的驅動名,確保使用如'ODBCDriver17forSQLServer'等正確驅動名稱;4.連接字符串關鍵參數

使用httpx.AsyncClient可高效发起异步HTTP请求,1.基本GET请求通过asyncwith管理客户端并用awaitclient.get发起非阻塞请求;2.并发多个请求时结合asyncio.gather可显著提升性能,总耗时等于最慢请求;3.支持自定义headers、认证、base_url和超时设置;4.可发送POST请求并携带JSON数据;5.注意避免混用同步异步代码,代理支持需注意后端兼容性,适合用于爬虫或API聚合等场景。

pythoncanbeoptimizedFormized-formemory-boundoperationsbyreducingOverHeadThroughGenerator,有效dattratsures,andManagingObjectLifetimes.first,useGeneratorSInsteadoFlistSteadoflistSteadoFocessLargedAtasetSoneItematatime,desceedingingLoadeGingloadInterveringerverneDraineNterveingerverneDraineNterveInterveIntMory.second.second.second.second,Choos,Choos

本文旨在幫助 SQLAlchemy 初學者解決在使用 create_engine 時遇到的 "RemovedIn20Warning" 警告,以及隨之而來的 "ResourceClosedError" 連接關閉錯誤。文章將詳細解釋該警告的原因,並提供消除警告以及修復連接問題的具體步驟和代碼示例,確保你能夠順利地查詢和操作數據庫。

shutil.rmtree()是Python中用於遞歸刪除整個目錄樹的函數,能刪除指定文件夾及其所有內容。 1.基本用法:使用shutil.rmtree(path)刪除目錄,需處理FileNotFoundError、PermissionError等異常。 2.實際應用:可一鍵清除包含子目錄和文件的文件夾,如臨時數據或緩存目錄。 3.注意事項:刪除操作不可恢復;路徑不存在時拋出FileNotFoundError;可能因權限或文件佔用導致失敗。 4.可選參數:可通過ignore_errors=True忽略錯

安裝對應數據庫驅動;2.使用connect()連接數據庫;3.創建cursor對象;4.用execute()或executemany()執行SQL並用參數化查詢防注入;5.用fetchall()等獲取結果;6.修改後需commit();7.最後關閉連接或使用上下文管理器自動處理;完整流程確保安全且高效執行SQL操作。

Python是實現ETL流程的高效工具,1.數據抽取:通過pandas、sqlalchemy、requests等庫可從數據庫、API、文件等來源提取數據;2.數據轉換:使用pandas進行清洗、類型轉換、關聯、聚合等操作,確保數據質量並優化性能;3.數據加載:利用pandas的to_sql方法或云平台SDK將數據寫入目標系統,注意寫入方式與批次處理;4.工具推薦:Airflow、Dagster、Prefect用於流程調度與管理,結合日誌報警與虛擬環境提升穩定性與可維護性。

在JupyterNotebook中使用PandasStyling可實現DataFrame的美觀展示,1.使用highlight_max和highlight_min高亮每列最大值(綠色)和最小值(紅色);2.通過background_gradient為數值列添加漸變背景色(如Blues或Reds)以直觀顯示數據大小;3.自定義函數color_score結合applymap為不同分數區間設置文字顏色(≥90綠色,80~89橙色,60~79紅色,
