python读取.env配置⽂件python 读取.env配置⽂件
⽬录结构
project/
├─config
│└─__init__.py
|└─base.py
|└─conf.py
├─.env
├─.ample
conf.py
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Author : Charlie Zhang
# @Email : charlie.zhang@wiwide
# @Time : 2021/7/20 16:40
# @Version : 1.0
# @File : conf.py
# @Software : PyCharm
import os
import typing
from collections.abc import MutableMapping
from pathlib import Path
class undefined:
pass
class EnvironError(Exception):
pass
class Environ(MutableMapping):
def__init__(self, environ: typing.MutableMapping = os.environ):
self._environ = environ
self._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.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:
(key, cast, default)
def get(
self, key:str, cast: typing.Callable =None, default: typing.Any = undefined, )-> typing.Any:
if key viron:
value = viron[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 adlines():
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]= value
return file_values
def_perform_cast(
self, key:str, value: typing.Any, cast: typing.Callable =None,
)-> typing.Any:
python怎么读取py文件
if cast is None or value is None:
return value
elif 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
BASE_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 = ""
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论