国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

[python]常用配置讀取方法

這篇具有很好參考價(jià)值的文章主要介紹了[python]常用配置讀取方法。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

前言

常見(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類(lèi)型為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è)字典類(lèi)型,通過(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類(lèi)型,都可以直接使用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í)行輸出文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-777068.html

{'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'}}

到了這里,關(guān)于[python]常用配置讀取方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • opencv基礎(chǔ): 視頻,攝像頭讀取與保存的常用方法

    opencv基礎(chǔ): 視頻,攝像頭讀取與保存的常用方法

    當(dāng)然還可以從視頻中抓取截圖,所以現(xiàn)在聊一下常用的抓取視頻截圖的的方法。 上面有三種構(gòu)造方法, 第一種是無(wú)法構(gòu)造方法。 第二種參數(shù)device是一個(gè)數(shù)字。 一般筆記本如此寫(xiě)cv2.VideoCapture(0); 因?yàn)槟J(rèn)是0 ,如果有多個(gè)攝像頭,就需要看設(shè)置的攝像頭代表的數(shù)字了。 第二種

    2024年02月09日
    瀏覽(29)
  • Python:實(shí)現(xiàn)文件讀取與輸入,數(shù)據(jù)存儲(chǔ)與讀取的常用命令

    Python:實(shí)現(xiàn)文件讀取與輸入,數(shù)據(jù)存儲(chǔ)與讀取的常用命令

    文本文件可用于存儲(chǔ)大量的數(shù)據(jù),里面的數(shù)據(jù)對(duì)于用戶而言十分重要,因此,本文就如何利用Python實(shí)現(xiàn)文本內(nèi)容的讀取與輸入,數(shù)據(jù)存儲(chǔ)與讀取進(jìn)行介紹。 一、讀取文件中的數(shù)據(jù): 首先需要找到所需文件的路徑:例如我在桌面創(chuàng)建了一個(gè)文本文件,它的路徑為 利用函數(shù) op

    2023年04月08日
    瀏覽(21)
  • 【數(shù)據(jù)處理】Pandas讀取CSV文件示例及常用方法(入門(mén))

    【數(shù)據(jù)處理】Pandas讀取CSV文件示例及常用方法(入門(mén))

    查看讀取前10行數(shù)據(jù) 2067 向前填充 指定列的插值填充 使用某數(shù)據(jù)填充指定列的空值 示例: 類(lèi)似切片 array([‘SE’, ‘cv’, ‘NW’, ‘NE’], dtype=object) 類(lèi)似數(shù)據(jù)庫(kù)查詢中的groupby查詢 先添加新的一列按月將數(shù)據(jù)劃分 聚合,對(duì)指定的列按月劃分求平均值等 min 最小值 max 最大值 sum

    2024年02月06日
    瀏覽(1673)
  • java中pdfbox處理pdf常用方法(讀取、寫(xiě)入、合并、拆分、寫(xiě)文字、寫(xiě)圖片)

    java中pdfbox處理pdf常用方法(讀取、寫(xiě)入、合并、拆分、寫(xiě)文字、寫(xiě)圖片)

    方法代碼: 測(cè)試用例: 2.1寫(xiě)文字 方法代碼: 測(cè)試用例: A.pdf: A2.pdf: 2.2寫(xiě)圖片 方法代碼: 測(cè)試用例: A.pdf: pic.jpg: A2.pdf: 方法代碼: 測(cè)試用例: 方法代碼: 測(cè)試用例: 引用鏈接: (17條消息) 使用Apache PDFBox實(shí)現(xiàn)拆分、合并PDF_似有風(fēng)中泣的博客-CSDN博客 (17條消息) Java使用P

    2024年02月11日
    瀏覽(32)
  • Yaml配置文件讀取方法

    在日常的代碼中,有一些值是配置文件中定義的,這些值可以根據(jù)用戶的要求進(jìn)行調(diào)整和改變。這往往會(huì)寫(xiě)在yaml格式的文件中。這樣開(kāi)放程序給用戶時(shí),就可以不必開(kāi)放對(duì)應(yīng)的源碼,只開(kāi)放yaml格式的配置文件即可。 將配置文件中的值讀入程序也非常的簡(jiǎn)單。 我們先寫(xiě)一個(gè)簡(jiǎn)

    2024年02月11日
    瀏覽(103)
  • Vector-常用CAN工具 - CANoe遷移常見(jiàn)Port配置問(wèn)題

    Vector-常用CAN工具 - CANoe遷移常見(jiàn)Port配置問(wèn)題

    ????????從 CANoe 和 CANalyzer 12.0 SP4 版本開(kāi)始,以太網(wǎng) 遷移向?qū)?將在必要時(shí)自動(dòng)開(kāi)始將現(xiàn)有工具配置轉(zhuǎn)換為新的 基于端口的網(wǎng)絡(luò)訪問(wèn)格式。 盡管大多數(shù)現(xiàn)有配置都可以毫無(wú)問(wèn)題地轉(zhuǎn)換,但有些可能不會(huì)。如果在遷移過(guò)程中遇到問(wèn)題, 遷移向?qū)?將通過(guò)以下可能的問(wèn)題消息提

    2024年02月07日
    瀏覽(22)
  • SpringBoot框架——8.MybatisPlus常見(jiàn)用法(常用注解+內(nèi)置方法+分頁(yè)查詢)

    SpringBoot框架——8.MybatisPlus常見(jiàn)用法(常用注解+內(nèi)置方法+分頁(yè)查詢)

    1.MybatisPlus常用注解: ? ? ? ? 1.1 當(dāng)數(shù)據(jù)庫(kù)、表名和字段名和實(shí)體類(lèi)完全一致時(shí)無(wú)需加注解,不一致時(shí): ? ? ? ? @TableName指定庫(kù)名 ? ? ? ? @TableId指定表名 ? ? ? ? @TableField指定字段名 ? ? ? ? 1.2 自增主鍵: ????????@TableId(type=IdType.AUTO) ? ? ? ? private Long id; ? ? ? ?

    2024年04月26日
    瀏覽(19)
  • C#文件讀取的全局配置編程方法

    C#怎樣在類(lèi)庫(kù)或者應(yīng)用入口從配置文件讀取參數(shù),并作用到全局。 面向?qū)ο蟮某绦蛴泻芏囝?lèi)庫(kù)分布在很多cs文件,如何全局起作用。 如何從可讀可編輯的文本導(dǎo)入配置。 靜態(tài)類(lèi)保存全局變量。 json文件保存,可讀。Newtonsoft.json 軟件導(dǎo)入方便。 關(guān)于newtonsoft開(kāi)源許可:\\\"Json.NET

    2024年02月14日
    瀏覽(32)
  • 常見(jiàn)的Web安全漏洞有哪些,Web安全漏洞常用測(cè)試方法介紹

    常見(jiàn)的Web安全漏洞有哪些,Web安全漏洞常用測(cè)試方法介紹

    Web安全漏洞是指在Web應(yīng)用程序中存在的可能被攻擊者利用的漏洞,正確認(rèn)識(shí)和了解這些漏洞對(duì)于Web應(yīng)用程序的開(kāi)發(fā)和測(cè)試至關(guān)重要。 一、常見(jiàn)的Web安全漏洞類(lèi)型: 1、跨站腳本攻擊(Cross-Site Scripting,XSS):攻擊者通過(guò)向Web頁(yè)面注入惡意腳本來(lái)執(zhí)行惡意操作,例如竊取用戶敏感信

    2024年02月11日
    瀏覽(19)
  • JAVA-9-[SpringBoot]非web應(yīng)用程序創(chuàng)建和配置文件讀取

    SpringBoot 常用讀取配置文件的 3 種方法! Spring Boot非web應(yīng)用程序的創(chuàng)建方式 有時(shí)有些項(xiàng)目不需要提供web服務(wù),比如跑定時(shí)任務(wù)的項(xiàng)目,如果都是按照web項(xiàng)目啟動(dòng),這個(gè)時(shí)候會(huì)浪費(fèi)一些資源。 1、Spring CommandLinerunner接口實(shí)現(xiàn)booot入口類(lèi); 2、run()方法覆蓋commandlineruner接口,在run方

    2023年04月08日
    瀏覽(33)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包