Henry
发布于 2025-03-11 / 9 阅读
0
0

Python - 使用 .env 配置文件来管理敏感信息

背景简介

使用.env配置文件管理敏感信息,可以避免将敏感数据硬编码在代码中,提高安全性。同时,便于在不同环境(开发、测试、生产)之间切换配置,简化部署流程,降低配置错误风险,使得项目管理更加灵活和可维护。

环境信息

  1. Python 已安装 【Conda - 配置 Python

详细步骤

第一步: 安装 Python 依赖

$ pip install python-dotenv
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting python-dotenv
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/6a/3e/b68c118422ec867fa7ab88444e1274aa40681c606d59ac27de5a5588f082/python_dotenv-1.0.1-py3-none-any.whl (19 kB)
Installing collected packages: python-dotenv
Successfully installed python-dotenv-1.0.1

第二步: 配置 .env 文件

MY_TEST_ENV = "This is a test env value for testing"

第三步: 实现简易 demo,示例文件名: env-demo.py  。

# 导入 os 库
import os

# 导入dotenv库
from dotenv import load_dotenv

# 导入环境变量
load_dotenv('./.env')

# 获取环境变量的值
my_test_env_value = os.getenv('MY_TEST_ENV')

# 打印查看
print(my_test_env_value)

第四步: 执行 demo。

$ python env-demo.py 

This is a test env value for testing

以上便是本文的全部内容,感谢您的阅读,如遇到任何问题,欢迎在评论区留言讨论。



评论