python-dotenv - python-dotenv 快速上手

python-dotenv 概述

  • python-dotenv 是一个允许开发者从 .env 文件中读取环境变量的一个 Python 库

python-dotenv 使用

  1. 安装 python-dotenv 库
shell 复制代码
pip install python-dotenv
  1. 创建并编辑 .env 文件
env 复制代码
SECRET_KEY=my-secret-key-123
DATABASE_URL=postgresql://user:password@localhost/dbname
DEBUG=True
API_KEY=my-api-key-123
MAX_CONNECTIONS=10
  1. 在 Python 代码中读取环境变量
python 复制代码
from dotenv import load_dotenv
import os

# 加载 .env 文件中的环境变量
load_dotenv()

# 访问 .env 文件中的环境变量
secret_key = os.getenv('SECRET_KEY')
database_url = os.getenv('DATABASE_URL')
debug = os.getenv('DEBUG')
api_key = os.getenv('API_KEY')
max_connections = os.getenv('MAX_CONNECTIONS')

other_content = os.getenv('OTHER_CONTENT')

print(f"Secret Key: {secret_key}, type: {type(secret_key)}")
print(f"Database URL: {database_url} type: {type(database_url)}")
print(f"Debug Mode: {debug}, type: {type(debug)}")
print(f"API Key: {api_key}, type: {type(api_key)}")
print(f"Max Connections: {max_connections}, type: {type(max_connections)}")

print(f"Other Content: {other_content}, type: {type(other_content)}")
复制代码
# 输出结果

Secret Key: my-secret-key-123, type: <class 'str'>
Database URL: postgresql://user:password@localhost/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 的操作系统接口模块,此模块提供与操作系统交互的各种功能,对于获取环境变量,有如下方式
  1. os.getenv():安全,推荐使用,不存在时返回 None,可以指定默认值

  2. os.environ\[\]:直接访问,如果不存在会抛出异常

  3. os.environ.get():与 os.getenv() 功能相同

相关推荐
青山是哪个青山5 小时前
LangChain 学习笔记(四):Message 与提示词模板
笔记·学习·langchain
小白勇闯网安圈5 小时前
Django 响应对象、文件上传与类视图
数据库·django·sqlite
从零开始学习人工智能6 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
hsjiasb6 小时前
FreeRTOS学习(二十六)——动态内存管理heap_1到heap_5
stm32·单片机·学习·学习笔记·freertos
崇子嵘6 小时前
基于zynqMP15eg的linux驱动学习
学习
努力的小雨6 小时前
同一份 SQL 跑多套环境:Ksql 变量怎么用才安全
数据库
东风破_6 小时前
ESLint 是什么?为什么你的项目需要它?
前端·后端·代码规范
嘻哈∠※6 小时前
0061基于 SpringBoot 的投稿与稿件处理系统设计与实现
java·spring boot·后端
WWJA王文举7 小时前
I²C通信完整流程详解:START、地址、ACK、数据、Repeated START和STOP一次讲透
c语言·开发语言
科技绘图7 小时前
快鲸GEO vs 传统AI搜索优化:全链路自动化与高效内容生产在转化闭环上的对比
数据库·人工智能·自动化