最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解python中常用配置的讀取方法

 更新時(shí)間:2024年01月09日 08:41:19   作者:花酒鋤作田  
常見(jiàn)的應(yīng)用配置方式有環(huán)境變量和配置文件,對(duì)于微服務(wù)應(yīng)用,還會(huì)從配置中心加載配置,本文主要介紹了從環(huán)境變量、.env文件、.ini文件、.yaml文件等文件的讀取配置,需要的可以參考下

前言

常見(jiàn)的應(yīng)用配置方式有環(huán)境變量和配置文件,對(duì)于微服務(wù)應(yīng)用,還會(huì)從配置中心加載配置,比如nacos、etcd等,有的應(yīng)用還會(huì)把部分配置寫(xiě)在數(shù)據(jù)庫(kù)中。此處主要記錄從環(huán)境變量、.env文件、.ini文件、.yaml文件、.toml文件、.json文件讀取配置。

ini文件

ini文件格式一般如下:

[mysql]
type = "mysql"
host = "127.0.0.1"
port = 3306
username = "root"
password = "123456"
dbname = "test"

[redis]
host = "127.0.0.1"
port = 6379
password = "123456"
db = "5"

使用python標(biāo)準(zhǔn)庫(kù)中的configparser可以讀取ini文件。

import configparser
import os

def read_ini(filename: str = "conf/app.ini"):
    """
    Read configuration from ini file.
    :param filename: filename of the ini file
    """
    config = configparser.ConfigParser()
    if not os.path.exists(filename):
        raise FileNotFoundError(f"File {filename} not found")
    config.read(filename, encoding="utf-8")
    return config

config類型為configparser.ConfigParser,可以使用如下方式讀取

config = read_ini("conf/app.ini")

for section in config.sections():
    for k,v in config.items(section):
        print(f"{section}.{k}: {v}")

讀取輸出示例

mysql.type: "mysql"
mysql.host: "127.0.0.1"
mysql.port: 3306
mysql.username: "root"
mysql.password: "123456"
mysql.dbname: "test"
redis.host: "127.0.0.1"
redis.port: 6379
redis.password: "123456"
redis.db: "5"

yaml文件

yaml文件內(nèi)容示例如下:

database:
  mysql:
    host: "127.0.0.1"
    port: 3306
    user: "root"
    password: "123456"
    dbname: "test"
  redis:
    host: 
      - "192.168.0.10"
      - "192.168.0.11"
    port: 6379
    password: "123456"
    db: "5"

log:
  directory: "logs"
  level: "debug"
  maxsize: 100
  maxage: 30
  maxbackups: 30
  compress: true

讀取yaml文件需要安裝pyyaml

pip install pyyaml

讀取yaml文件的示例代碼

import yaml
import os

def read_yaml(filename: str = "conf/app.yaml"):
    if not os.path.exists(filename):
        raise FileNotFoundError(f"File {filename} not found")
    with open(filename, "r", encoding="utf-8") as f:
        config = yaml.safe_load(f.read())
        return config
    
if __name__ == "__main__":
    config = read_yaml("conf/app.yaml")
    print(type(config))
    print(config)

執(zhí)行輸出,可以看到config是個(gè)字典類型,通過(guò)key就可以訪問(wèn)到

<class 'dict'>
{'database': {'mysql': {'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'password': '123456', 'dbname': 'test'}, 'redis': {'host': ['192.168.0.10', '192.168.0.11'], 'port': 6379, 'password': '123456', 'db': '5'}}, 'log': {'directory': 'logs', 'level': 'debug', 'maxsize': 100, 'maxage': 30, 'maxbackups': 30, 'compress': True}}

toml文件

toml文件比較像yaml,但是不要求縮進(jìn)格式。如果比較討厭yaml的縮進(jìn)問(wèn)題,那么可以考慮下使用toml。一個(gè)簡(jiǎn)單的toml文件示例如下:

[database]
dbtype = "mysql"

[database.mysql]
host = "127.0.0.1"
port = 3306
user = "root"
password = "123456"
dbname = "test"

[database.redis]
host = ["192.168.0.10", "192.168.0.11"]
port = 6379
password = "123456"
db = "5"

[log]
directory = "logs"
level = "debug"

如果python版本高于3.11,其標(biāo)準(zhǔn)庫(kù)tomllib就可以讀取toml文件。讀取toml文件的第三方庫(kù)也有很多,個(gè)人一般使用toml

pip install toml

讀取toml文件的示例代碼

import tomllib # python version >= 3.11
import toml
import os

def read_toml_1(filename: str = "conf/app.toml"):
    """ 
    Read configuration from toml file using tomllib that is python standard package.
    Python version >= 3.11
    """
    if not os.path.exists(filename):
        raise FileNotFoundError(f"File {filename} not found")
    with open(filename, "rb") as f:
        config = tomllib.load(f)
        return config
    
def read_toml_2(filename: str = "conf/app.toml"):
    """
    Read configuration from toml file using toml package.
    """
    if not os.path.exists(filename):
        raise FileNotFoundError(f"File {filename} not found")
    
    with open(filename, "r" ,encoding="utf-8") as f:
        config = toml.load(f)
        return config
    
if __name__ == "__main__":
    config = read_toml_1("conf/app.yaml")
    # config = read_toml_2("conf/app.yaml")
    print(type(config))
    print(config)

執(zhí)行輸出,無(wú)論使用tomllibtoml,返回的都是dict類型,都可以直接使用key訪問(wèn)。

<class 'dict'>
{'database': {'mysql': {'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'password': '123456', 'dbname': 'test'}, 'redis': {'host': ['192.168.0.10', '192.168.0.11'], 'port': 6379, 'password': '123456', 'db': '5'}}, 'log': {'directory': 'logs', 'level': 'debug', 'maxsize': 100, 'maxage': 30, 'maxbackups': 30, 'compress': True}}

json文件

使用標(biāo)準(zhǔn)庫(kù)json即可讀取json文件,json配置文件示例:

{
    "database": {
        "mysql": {
            "host": "127.0.0.1",
            "port": 3306,
            "user": "root",
            "password": "123456",
            "dbname": "test"
        },
        "redis": {
            "host": [
                "192.168.0.10",
                "192.168.0.11"
            ],
            "port": 6379,
            "password": "123456",
            "db": "5" 
        }
    },
    "log": {
        "level": "debug",
        "dir": "logs"
    }
}

解析的示例代碼如下

import json
import os

def read_json(filename: str = "conf/app.json") -> dict:
    """
    Read configuration from json file using json package.
    """
    if not os.path.exists(filename):
        raise FileNotFoundError(f"File {filename} not found")
    with open(filename, "r", encoding="utf-8") as f:
        config = json.load(f)
        return config
    
if __name__ == "__main__":
    config = read_json("conf/app.yaml")
    print(type(config))
    print(config)

執(zhí)行輸出

<class 'dict'>
{'database': {'mysql': {'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'password': '123456', 'dbname': 'test'}, 'redis': {'host': ['192.168.0.10', '192.168.0.11'], 'port': 6379, 'password': '123456', 'db': '5'}}, 'log': {'level': 'debug', 'dir': 'logs'}}

.env文件

.env文件讀取鍵值對(duì)配置,并將它們添加到環(huán)境變量中,添加后可以使用os.getenv()獲取。

讀取.env文件需要安裝第三方庫(kù)

pip install python-dotenv

.env文件示例

MYSQL_HOST="127.0.0.1"
MYSQL_PORT=3306
MYSQL_USERNAME="root"
MYSQL_PASSWORD="123456"
MYSQL_DATABASE="test"

示例代碼

import os
import dotenv

def read_dotenv(filename: str = "conf/.env"):
    if not os.path.exists(filename):
        raise FileNotFoundError(f"File {filename} not found")
    load_dotenv(dotenv_path=filename, encoding="utf-8", override=True)
    config = dict(os.environ)
    return config

if __name__ == "__main__":
    config = read_json("conf/app.yaml")
    for k,v in config.items():
        if k.startswith("MYSQL_"):
            print(f"{k}: {v}")

讀取環(huán)境變量

在標(biāo)準(zhǔn)庫(kù)os中有以下常用的和環(huán)境變量相關(guān)的方法,具體可參考官方文檔:https://docs.python.org/zh-cn/3/library/os.html

os.environ,一個(gè)mapping對(duì)象,其中鍵值是代表進(jìn)程環(huán)境的字符串。例如 environ["HOME"]

# example
import os
config = dict(os.environ)
for k,v in config.items():
    print(k,v)

os.getenv(key, default=None)。如果環(huán)境變量 key 存在則將其值作為字符串返回,如果不存在則返回 default。

os.putenv(key, value)。設(shè)置環(huán)境變量,官方文檔推薦直接修改os.environ。例如:os.putenv("MYSQL_HOST", "127.0.0.1")

os.unsetenv(key)。刪除名為 key 的環(huán)境變量,官方文檔推薦直接修改os.environ。例如:os.unsetenv("MYSQL_HOST")

綜合示例

一般來(lái)說(shuō)配置解析相關(guān)代碼會(huì)放到單獨(dú)的包中,配置文件也會(huì)放到單獨(dú)的目錄,這里給個(gè)簡(jiǎn)單的示例。

目錄結(jié)構(gòu)如下,conf目錄存放配置文件,pkg/config.py用于解析配置,main.py為程序入口。

.
├── conf
│   ├── app.ini
│   ├── app.json
│   ├── app.toml
│   └── app.yaml
├── main.py
└── pkg
    ├── config.py
    └── __init__.py

pkg/__init__.py文件為空,pkg/config.py內(nèi)容如下:

import configparser
import os
import yaml
import tomllib
import json
import abc
from dotenv import load_dotenv

class Configer(metaclass=abc.ABCMeta):
    def __init__(self, filename: str):
        self.filename = filename

    @abc.abstractmethod
    def load(self):
        raise NotImplementedError(f"subclass must implement this method")
    
    def file_exists(self):
        if not os.path.exists(self.filename):
            raise FileNotFoundError(f"File {self.filename} not found")

class IniParser(Configer):
    def __init__(self, filename: str):
        super().__init__(filename)

    def load(self):
        super().file_exists()
        config = configparser.ConfigParser()
        config.read(self.filename, encoding="utf-8")
        return config

class YamlParser(Configer):
    def __init__(self, filename: str):
        super().__init__(filename)

    def load(self):
        super().file_exists()
        with open(self.filename, "r", encoding="utf-8") as f:
            config = yaml.safe_load(f.read())
            return config

class TomlParser(Configer):
    def __init__(self, filename: str):
        super().__init__(filename)

    def load(self):
        super().file_exists()
        with open(self.filename, "rb") as f:
            config = tomllib.load(f)
            return config
        
class JsonParser(Configer):
    def __init__(self, cfgtype: str, filename: str = None):
        super().__init__(cfgtype, filename)

    def load(self):
        super().file_exists()
        with open(self.filename, "r", encoding="utf-8") as f:
            config = json.load(f)
            return config
        
class DotenvParser(Configer):
    def __init__(self, filename: str = None):
        super().__init__(filename)

    def load(self):
        super().file_exists()
        load_dotenv(self.filename, override=True)
        config = dict(os.environ)
        return config

main.py示例:

from pkg.config import TomlParser

config = TomlParser("conf/app.toml")
print(config.load())

執(zhí)行輸出

{'database': {'dbtype': 'mysql', 'mysql': {'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'password': '123456', 'dbname': 'test'}, 'redis': {'host': ['192.168.0.10', '192.168.0.11'], 'port': 6379, 'password': '123456', 'db': '5'}}, 'log': {'directory': 'logs', 'level': 'debug'}}

以上就是詳解python中常用配置的讀取方法的詳細(xì)內(nèi)容,更多關(guān)于python配置讀取的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python使用xlrd和xlwt批量讀寫(xiě)excel文件的示例代碼

    Python使用xlrd和xlwt批量讀寫(xiě)excel文件的示例代碼

    這篇文章主要介紹了Python使用xlrd和xlwt批量讀寫(xiě)excel文件,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-03-03
  • python多進(jìn)程實(shí)現(xiàn)文件下載傳輸功能

    python多進(jìn)程實(shí)現(xiàn)文件下載傳輸功能

    這篇文章主要為大家詳細(xì)介紹了python多進(jìn)程實(shí)現(xiàn)文件下載傳輸功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • Python編程中的常用模塊詳解

    Python編程中的常用模塊詳解

    本文介紹了Python常用的time、datetime、random、os、sys、json和pickle模塊的用途及常見(jiàn)用法,包括時(shí)間處理、操作系統(tǒng)交互、進(jìn)度條實(shí)現(xiàn)以及數(shù)據(jù)序列化等內(nèi)容,感興趣的朋友跟隨小編一起看看吧
    2025-10-10
  • Python將8位的圖片轉(zhuǎn)為24位的圖片實(shí)現(xiàn)方法

    Python將8位的圖片轉(zhuǎn)為24位的圖片實(shí)現(xiàn)方法

    這篇文章主要介紹了Python將8位的圖片轉(zhuǎn)為24位的圖片的實(shí)現(xiàn)代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-10-10
  • pyecharts繪制各種數(shù)據(jù)可視化圖表案例附效果+代碼

    pyecharts繪制各種數(shù)據(jù)可視化圖表案例附效果+代碼

    這篇文章主要介紹了pyecharts繪制各種數(shù)據(jù)可視化圖表案例并附效果和代碼,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,感興趣的小伙伴可以參考一下
    2022-06-06
  • 使用Python的turtle模塊畫(huà)國(guó)旗

    使用Python的turtle模塊畫(huà)國(guó)旗

    這篇文章主要為大家詳細(xì)介紹了用Python的turtle模塊畫(huà)國(guó)旗,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-09-09
  • 如何定義TensorFlow輸入節(jié)點(diǎn)

    如何定義TensorFlow輸入節(jié)點(diǎn)

    今天小編就為大家分享一篇如何定義TensorFlow輸入節(jié)點(diǎn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-01-01
  • python opencv根據(jù)顏色進(jìn)行目標(biāo)檢測(cè)的方法示例

    python opencv根據(jù)顏色進(jìn)行目標(biāo)檢測(cè)的方法示例

    這篇文章主要介紹了python opencv根據(jù)顏色進(jìn)行目標(biāo)檢測(cè)的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-01-01
  • Python導(dǎo)入torch包的完整方法過(guò)程

    Python導(dǎo)入torch包的完整方法過(guò)程

    這篇文章主要給大家介紹了關(guān)于Python導(dǎo)入torch包的完整方法, python torch又稱PyTorach,是一個(gè)以Python優(yōu)先的深度學(xué)習(xí)框架,一個(gè)開(kāi)源的Python機(jī)器學(xué)習(xí)庫(kù),用于自然語(yǔ)言處理等應(yīng)用程序,需要的朋友可以參考下
    2023-12-12
  • python利用smtplib實(shí)現(xiàn)QQ郵箱發(fā)送郵件

    python利用smtplib實(shí)現(xiàn)QQ郵箱發(fā)送郵件

    這篇文章主要為大家詳細(xì)介紹了python利用smtplib實(shí)現(xiàn)QQ郵箱發(fā)送郵件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-05-05

最新評(píng)論

宣化县| 朝阳区| 高密市| 乌拉特前旗| 武胜县| 琼结县| 华安县| 贵溪市| 九江市| 安阳市| 平邑县| 武胜县| 纳雍县| 施秉县| 壶关县| 汽车| 偃师市| 云龙县| 苏尼特右旗| 宁国市| 镶黄旗| 轮台县| 新化县| 美姑县| 商水县| 孝感市| 泸州市| 海阳市| 澜沧| 汉沽区| 宾阳县| 道孚县| 蚌埠市| 柳河县| 夏河县| 海晏县| 贵港市| 西充县| 卓资县| 泸溪县| 阿合奇县|