2026/1/28 8:22:14
网站建设
项目流程
包头网站建设推广,开封网站建设中心,住建部网站查询系统,建站网址大全python-dotenv 概述
python-dotenv 是一个允许开发者从 .env 文件中读取环境变量的一个 Python 库python-dotenv 使用
安装 python-dotenv 库
pip install python-dotenv创建并编辑 .env 文件
SECRET_KEYmy-secret-key-123
DATABASE_URLpostgresql://user:passwordlocalhost/db…python-dotenv 概述python-dotenv 是一个允许开发者从.env文件中读取环境变量的一个 Python 库python-dotenv 使用安装 python-dotenv 库pipinstallpython-dotenv创建并编辑.env文件SECRET_KEYmy-secret-key-123 DATABASE_URLpostgresql://user:passwordlocalhost/dbname DEBUGTrue API_KEYmy-api-key-123 MAX_CONNECTIONS10在 Python 代码中读取环境变量fromdotenvimportload_dotenvimportos# 加载 .env 文件中的环境变量load_dotenv()# 访问 .env 文件中的环境变量secret_keyos.getenv(SECRET_KEY)database_urlos.getenv(DATABASE_URL)debugos.getenv(DEBUG)api_keyos.getenv(API_KEY)max_connectionsos.getenv(MAX_CONNECTIONS)other_contentos.getenv(OTHER_CONTENT)print(fSecret Key:{secret_key}, type:{type(secret_key)})print(fDatabase URL:{database_url}type:{type(database_url)})print(fDebug Mode:{debug}, type:{type(debug)})print(fAPI Key:{api_key}, type:{type(api_key)})print(fMax Connections:{max_connections}, type:{type(max_connections)})print(fOther Content:{other_content}, type:{type(other_content)})# 输出结果 Secret Key: my-secret-key-123, type: class str Database URL: postgresql://user:passwordlocalhost/dbname type: class str Debug Mode: True, type: class str API Key: my-api-key-123, type: class str Max Connections: 10, type: class str Other Content: None, type: class NoneType补充学习import os用于导入 Python 的操作系统接口模块此模块提供与操作系统交互的各种功能对于获取环境变量有如下方式os.getenv()安全推荐使用不存在时返回 None可以指定默认值os.environ[]直接访问如果不存在会抛出异常os.environ.get()与 os.getenv() 功能相同