news 2026/7/3 13:37:19

python-dotenv - python-dotenv 快速上手

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
python-dotenv - python-dotenv 快速上手

python-dotenv 概述

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

python-dotenv 使用

  1. 安装 python-dotenv 库
pipinstallpython-dotenv
  1. 创建并编辑.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 代码中读取环境变量
fromdotenvimportload_dotenvimportos# 加载 .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() 功能相同

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/7/2 6:45:24

Obsidian图像工具包:终极图片管理与编辑指南

Obsidian图像工具包&#xff1a;终极图片管理与编辑指南 【免费下载链接】obsidian-image-toolkit An Obsidian plugin for viewing an image. 项目地址: https://gitcode.com/gh_mirrors/ob/obsidian-image-toolkit Obsidian图像工具包是专为Obsidian笔记用户设计的强大…

作者头像 李华
网站建设 2026/7/3 8:40:00

自主高性价比、高精度车规级姿态感知、倾角感知模组-应用消费级无人机、自动驾驶、机器人、智能制造、基础设施、智能穿戴等

自主高性价比、高精度车规级姿态感知、倾角感知模组-应用消费级无人机、自动驾驶、机器人、智能制造、基础设施、智能穿戴等在小说阅读器中沉浸阅读IMU 惯性测量单元(Inertial Measurement Unit) 是测量物体三轴角速度和加速度的设备。一个IMU内可能会装有三轴陀螺仪和三轴加速…

作者头像 李华
网站建设 2026/7/1 4:10:18

ComfyUI智能修复技术:图像处理的革命性突破

ComfyUI智能修复技术&#xff1a;图像处理的革命性突破 【免费下载链接】ComfyUI-Inpaint-CropAndStitch ComfyUI nodes to crop before sampling and stitch back after sampling that speed up inpainting 项目地址: https://gitcode.com/gh_mirrors/co/ComfyUI-Inpaint-Cr…

作者头像 李华
网站建设 2026/7/2 13:11:19

碳硅协同:人工智能作为碳基生命合作伙伴的终极形态分析

碳硅协同&#xff1a;人工智能作为碳基生命合作伙伴的终极形态分析您的手绘草图与“碳硅协同”的理念相结合&#xff0c;完美地阐释了未来人工智能作为碳基生命&#xff08;人类&#xff09;合作伙伴的终极形态。这远非替代关系&#xff0c;而是一种共生式进化。以下是具体分析…

作者头像 李华