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

相关推荐
MC丶科42 分钟前
【SpringBoot常见报错与解决方案】中文乱码?Spring Boot 统一解决前后端中文乱码问题(含 Postman 测试)!别再百度“加 UTF-8”了!
spring boot·后端·postman
今晚务必早点睡2 小时前
微服务改数据库密码后服务仍能访问?一次“看似异常、实则常见”的生产现象全解析
数据库·微服务·oracle
leaves falling2 小时前
C语言内存函数-
c语言·开发语言
程序员:钧念2 小时前
深度学习与强化学习的区别
人工智能·python·深度学习·算法·transformer·rag
数据与后端架构提升之路3 小时前
TeleTron 源码揭秘:如何用适配器模式“无缝魔改” Megatron-Core?
人工智能·python·适配器模式
老师我太想进步了20263 小时前
cmd连接MySQL及相关查询
数据库·mysql
至为芯4 小时前
IP6537至为芯支持双C口快充输出的45W降压SOC芯片
c语言·开发语言
hele_two4 小时前
快速幂算法
c++·python·算法
yuanmenghao4 小时前
车载Linux 系统问题定位方法论与实战系列 - 车载 Linux 平台问题定位规范
linux·运维·服务器·网络·c++
小羊羊Python4 小时前
SoundMaze v1.0.1正式发布!
开发语言·c++