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 分钟前
C++基础
开发语言·c++
!chen6 分钟前
linux服务器静默安装Oracle26ai
linux·运维·服务器
IT·小灰灰6 分钟前
30行PHP,利用硅基流动API,网页客服瞬间上线
开发语言·人工智能·aigc·php
快点好好学习吧8 分钟前
phpize 依赖 php-config 获取 PHP 信息的庖丁解牛
android·开发语言·php
秦老师Q9 分钟前
php入门教程(超详细,一篇就够了!!!)
开发语言·mysql·php·db
烟锁池塘柳09 分钟前
解决Google Scholar “We‘re sorry... but your computer or network may be sending automated queries.”的问题
开发语言
是誰萆微了承諾9 分钟前
php 对接deepseek
android·开发语言·php
莫大3309 分钟前
2核2G云服务器PHP8.5+MySQL9.0+Nginx(LNMP)安装WordPress网站详细教程
运维·服务器·nginx
vx_BS8133013 分钟前
【直接可用源码免费送】计算机毕业设计精选项目03574基于Python的网上商城管理系统设计与实现:Java/PHP/Python/C#小程序、单片机、成品+文档源码支持定制
java·python·课程设计
2601_9498683613 分钟前
Flutter for OpenHarmony 电子合同签署App实战 - 已签合同实现
java·开发语言·flutter