python 读取.env配置文件
python 读取.env配置文件
目录结构
project/ ├─config │ └─__init__.py | └─base.py | └─conf.py ├─.env ├─.env.example
conf.py
#!/usr/bin/python3 # -*- coding:utf-8 -*- # @Author : Charlie Zhang # @Email : charlie.zhang@wiwide.com # @Time : 2021/7/20 16:40 # @Version : 1.0 # @File : conf.py # @Software : PyCharmimport os import typing from collections.abc import MutableMapping from pathlib import Pathclass undefined:passclass EnvironError(Exception):passclass Environ(MutableMapping):def __init__(self, environ: typing.MutableMapping = os.environ):self._environ = environself._has_been_read = set() # type: typing.Set[typing.Any]def __getitem__(self, key: typing.Any) -> typing.Any:self._has_been_read.add(key)return self._environ.__getitem__(key)def __setitem__(self, key: typing.Any, value: typing.Any) -> None:if key in self._has_been_read:raise EnvironError(f"Attempting to set environ['{key}'], but the value has already been read.")self._environ.__setitem__(key, value)def __delitem__(self, key: typing.Any) -> None:if key in self._has_been_read:raise EnvironError(f"Attempting to delete environ['{key}'], but the value has already been read.")self._environ.__delitem__(key)def __iter__(self) -> typing.Iterator:return iter(self._environ)def __len__(self) -> int:return len(self._environ)environ = Environ()class Config:def __init__(self,env_file: typing.Union[str, Path] = None,environ: typing.Mapping[str, str] = environ,) -> None:self.environ = environself.file_values = {} # type: typing.Dict[str, str]if env_file is not None and os.path.isfile(env_file):self.file_values = self._read_file(env_file)def __call__(self, key: str, cast: typing.Callable = None, default: typing.Any = undefined,) -> typing.Any:return self.get(key, cast, default)def get(self, key: str, cast: typing.Callable = None, default: typing.Any = undefined,) -> typing.Any:if key in self.environ:value = self.environ[key]return self._perform_cast(key, value, cast)if key in self.file_values:value = self.file_values[key]return self._perform_cast(key, value, cast)if default is not undefined:return self._perform_cast(key, default, cast)raise KeyError(f"Config '{key}' is missing, and has no default.")def _read_file(self, file_name: typing.Union[str, Path]) -> typing.Dict[str, str]:file_values = {} # type: typing.Dict[str, str]with open(file_name) as input_file:for line in input_file.readlines():line = line.strip()if "=" in line and not line.startswith("#"):key, value = line.split("=", 1)key = key.strip()value = value.strip().strip("\"'")file_values[key] = valuereturn file_valuesdef _perform_cast(self, key: str, value: typing.Any, cast: typing.Callable = None,) -> typing.Any:if cast is None or value is None:return valueelif cast is bool and isinstance(value, str):mapping = {"true": True, "1": True, "false": False, "0": False}value = value.lower()if value not in mapping:raise ValueError(f"Config '{key}' has value '{value}'. Not a valid bool.")return mapping[value]try:return cast(value)except (TypeError, ValueError):raise ValueError(f"Config '{key}' has value '{value}'. Not a valid {cast.__name__}.")
base.py
import os from .conf import ConfigBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) config = Config(os.path.join(BASE_DIR, ".env")) KAFKA_HOSTS: str = config('KAFKA_HOSTS', cast=str, default='192.168.4.54:9092')
init.py
from .base import *
.env
KAFKA_HOSTS = ""
python 读取.env配置文件相关推荐
- python读取yaml配置文件的方法
yaml简介 1.yaml [ˈjæməl]: Yet Another Markup Language :另一种标记语言.yaml 是专门用来写配置文件的语言,非常简洁和强大,之前用ini也能写配置文 ...
- python读取json配置文件_Python简单读取json文件功能示例
本文实例讲述了Python简单读取json文件功能.分享给大家供大家参考,具体如下: read_json.json: { "rule":{ "namespace" ...
- python读取nacos配置文件
安装依赖 pip install nacos-sdk-python 主体部分 import nacos import yamlSERVER_ADDRESS = "xxx.xx.xxx.xxx ...
- python读取配置文件获取所有键值对_python读取配置文件 变量 ConfigParser模块
Python 读取写入配置文件很方便,可使用内置的 configparser 模块 配置文件:config.ini [oppo] platformName = Android platformVers ...
- python读取配置文件获取所有键值对_Python读取properties配置文件操作示例
本文实例讲述了Python读取properties配置文件操作.分享给大家供大家参考,具体如下: 工作需要将Java项目的逻辑改为python执行,Java的很多配置文件都是.properties的, ...
- python configparser 数组_python读取ini配置文件,python中数组如何表示
python读取ini配置文件 Python必须使用configparser包来读取ini配置,因此首先加载它. 导入configparser后,我们需要加载配置文件. config=configpa ...
- 【自动化测试】Python 读取 .ini 格式文件
大家应该接触过.ini格式的配置文件.配置文件就是把一些配置相关信息提取出去来进行单独管理,如果以后有变动只需改配置文件,无需修改代码.特别是后续做自动化的测试,需要拎出一部分配置信息,进行管理.比如 ...
- python ini文件 遍历_【自动化测试】Python 读取 .ini 格式文件
大家应该接触过.ini格式的配置文件.配置文件就是把一些配置相关信息提取出去来进行单独管理,如果以后有变动只需改配置文件,无需修改代码.特别是后续做自动化的测试,需要拎出一部分配置信息,进行管理.比如 ...
- python读取配置文件获取所有键值对_python笔记14-读取yaml配置文件(pyyaml)
yaml简介 1.yaml [ˈjæməl]: Yet Another Markup Language :另一种标记语言.yaml 是专门用来写配置文件的语言,非常简洁和强大,之前用ini也能写配置文 ...
最新文章
- hive数据导入导出
- python可视化lassocv特征筛选之后的特征的相关性分析热力图
- Iphone4涨到2万,相对VERTU有里子,面子也便宜
- SAP 电商云 Spartacus UI Quick Order 延迟加载的现象分析
- mysql还是mdb2_mysql两种表存储结构myisam和innodb的性能比较测试
- mysql的unique_MySQL使用UNIQUE实现数据不重复插入
- 1.3编程基础之算术表达式与顺序执行 12 计算球的体积
- 什么情况下需要创建MySQL索引
- mysql no cache_关于对MySQL的SQL_NO_CACHE的理解和用法举例
- 图像分割学习笔记_1(opencv自带meanshift分割例子)
- 如何通过Google学术快速获取参考文献引用格式-2021年
- [SVM系列之一]白话支持向量机(SVM)
- android10 psp模拟器,PPSSPP(PSP模拟器) V1.10 安卓版
- OpenGL 入门 17:立方体贴图
- Python黑白转换程序
- 采购交期改善,这些表格一定要用上
- __FILE__显示全路径的问题
- JAVA特点优点以及环境
- 维修服务行业薪酬体系设计案例
- Visifire实现统计图