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() 功能相同

相关推荐
灵感菇_几秒前
Java 锁机制全面解析
java·开发语言
wdfk_prog2 分钟前
[Linux]学习笔记系列 -- [drivers][mmc][mmc_sdio]
linux·笔记·学习
果果燕9 分钟前
今日学习笔记:双向链表、循环链表、栈
笔记·学习·链表
wazmlp00188736913 分钟前
python第三次作业
开发语言·python
娇娇乔木14 分钟前
模块十一--接口/抽象方法/多态--尚硅谷Javase笔记总结
java·开发语言
觉醒大王18 分钟前
AI写的青基中了
人工智能·笔记·深度学习·学习·职场和发展·学习方法
明月醉窗台26 分钟前
qt使用笔记六之 Qt Creator、Qt Widgets、Qt Quick 详细解析
开发语言·笔记·qt
逍遥德27 分钟前
如何学编程之01.理论篇.如何通过阅读代码来提高自己的编程能力?
前端·后端·程序人生·重构·软件构建·代码规范
wangjialelele29 分钟前
平衡二叉搜索树:AVL树和红黑树
java·c语言·开发语言·数据结构·c++·算法·深度优先
深蓝电商API30 分钟前
住宅代理与数据中心代理在爬虫中的选择
爬虫·python