您应该如何使用环境变量配置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 (e.g., Heroku, AWS, GCP): Use platform-specific config commands or UI
- System level: Set in shell (e.g.,
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)

本文为您精选了多个顶级的Python“成品”项目网站与高水平“大片”级学习资源入口。无论您是想寻找开发灵感、观摩学习大师级的源代码,还是系统性地提升实战能力,这些平台都是不容错过的宝库,能帮助您快速成长为Python高手。

使用subprocess.run()可安全执行shell命令并捕获输出,推荐以列表传参避免注入风险;2.需要shell特性时可设shell=True,但需警惕命令注入;3.使用subprocess.Popen可实现实时输出处理;4.设置check=True可在命令失败时抛出异常;5.简单场景可直接链式调用获取输出;日常应优先使用subprocess.run(),避免使用os.system()或已弃用模块,以上方法覆盖了Python中执行shell命令的核心用法。

要入门量子机器学习(QML),首选工具是Python,需安装PennyLane、Qiskit、TensorFlowQuantum或PyTorchQuantum等库;接着通过运行示例熟悉流程,如使用PennyLane构建量子神经网络;然后按照数据集准备、数据编码、构建参数化量子线路、经典优化器训练等步骤实现模型;实战中应避免一开始就追求复杂模型,关注硬件限制,采用混合模型结构,并持续参考最新文献和官方文档以跟进发展。

使用Python调用WebAPI获取数据的关键在于掌握基本流程和常用工具。1.使用requests发起HTTP请求是最直接的方式,通过get方法获取响应并用json()解析数据;2.对于需要认证的API,可通过headers添加token或key;3.需检查响应状态码,推荐使用response.raise_for_status()自动处理异常;4.面对分页接口,可通过循环依次请求不同页面并加入延时避免频率限制;5.处理返回的JSON数据时需根据结构提取信息,复杂数据可用pandas转换为Data

使用Seaborn的jointplot可快速可视化两个变量间的关系及各自分布;2.基础散点图通过sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter")实现,中心为散点图,上下和右侧显示直方图;3.添加回归线和密度信息可用kind="reg",并结合marginal_kws设置边缘图样式;4.数据量大时推荐kind="hex",用

在Python中,使用join()方法合并字符串需注意以下要点:1.使用str.join()方法,调用时前面的字符串作为连接符,括号里的可迭代对象包含要连接的字符串;2.确保列表中的元素都是字符串,若含非字符串类型需先转换;3.处理嵌套列表时需先展平结构再连接。

字符串列表可用join()方法合并,如''.join(words)得到"HelloworldfromPython";2.数字列表需先用map(str,numbers)或[str(x)forxinnumbers]转为字符串后才能join;3.任意类型列表可直接用str()转换为带括号和引号的字符串,适用于调试;4.自定义格式可用生成器表达式结合join()实现,如'|'.join(f"[{item}]"foriteminitems)输出"[a]|[

掌握Python网络爬虫需抓住三个核心步骤:1.使用requests发起请求,通过get方法获取网页内容,注意设置headers、处理异常及遵守robots.txt;2.利用BeautifulSoup或XPath提取数据,前者适合简单解析,后者更灵活适用于复杂结构;3.针对动态加载内容使用Selenium模拟浏览器操作,虽速度较慢但能应对复杂页面,也可尝试寻找网站API接口提高效率。
