簡體   English   中英

如何通過 Python 中的 YAML 配置文件檢查與數據庫的連接?

[英]How to check connection to database via YAML configuration file in Python?

我有項目需要一個 YAML 配置文件來檢查與數據庫的連接,我有一些問題:如果特定於主機的沒有,它將自動成為默認值(本地主機)。 我已經用示例文件對其進行了測試

下面,但似乎我的代碼有問題,主機在為空時不會將默認值顯示為 loacalhost ,否則不顯示。 任何人都可以給我建議嗎? 我哪里錯了?

我的示例文件 data_source.yml:

database: 

dbopt:
   host: 
   port: 5432
   dbname: db1
   user: username
   password: 1234
   client_encoding: utf-8
   connect_timeout: 60
   sslmode: none

query:
   select * from manufacturing_product

query:
   select * from manufacturing_product

我的代碼:

import yaml

class InvalidConfigError(Exception):
    pass

class DB:
    def __init__(self, dbconf):
        self._dbconf = dict(dbconf)

        # checking for database type
        dbtype = self.get_db_type()
        if dbtype != 'sqlite' and dbtype != 'postgres':
            raise InvalidConfigError(
                'E01001', 'Invalid database type, should be sqlite or postgres.')
        else:
            self.dbtype = dbtype

        #checking db option
        dbopt = self.__get_dbopt()
        if dbopt is None:
            raise InvalidConfigError(
                'E01002', 'Invalid database options.')
        else:
            self.dbopt = dbopt

        #checking host
        host = dbopt.get('host')
        if host is None or len(host) <= 0:
            self.host = 'localhost'
        else:
            self.host = host

        #checking dbname
        dbname = dbopt.get('dbname')
        if dbname is None or len(dbname) <= 0:
            raise Exception("Database name is required.")
        else:
            self.dbname = dbname

    def get_db_type(self):
        return self._dbconf['db']

    def __get_dbopt(self):
        return self._dbconf.get('dbopt')

    def get_db_host(self):
        return self.host

    def get_db_name(self):
        return self.dbname

with open('data_source.yml') as file:
    data = yaml.full_load(file)

    for item, doc in data.items():
        print(item, ":", doc)

    db = DB(data)

輸出:

database: 

dbopt:
   host: 
   port: 5432
   dbname: db1
   user: username
   password: 1234
   client_encoding: utf-8
   connect_timeout: 60
   sslmode: none

query:
   select * from manufacturing_product

您的代碼很好,只是您沒有正確檢索它,我檢查並獲得了主機值為“localhost”

with open('data_source.yml') as file:
data = yaml.full_load(file)

for item, doc in data.items():
    print(item, ":", doc)

db = DB(data)

print("default host value:", db.get_db_host()) # added to test default host value 

輸出:

    db : postgres
dbopt : {'host': 'None', 'port': 1234, 'dbname': 'xyz', 'user': 'abc', 'password': 'pass', 'client_encoding': 'utf-8', 'connect_timeout': 100, 'sslmode': 'none'}
insopt : {'table': 'tries', 'out': 'qubna', 'bl': 'tghqua'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM