简体   繁体   中英

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

I have project need a YAML config file used to check connection to database and I have some issues: If host-specific is none, it will automatically be the default (localhost). I have tested it with sample file

below but it seem my code has a problem, the host does not display the default value as loacalhost when it is empty, otherwise it displays none. Can anyone suggest to me? Where am I wrong ?

My sample file 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

My code:

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)

Output:

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

your code is fine , just you are not retrieving it correctly ,I checked and got the host value as '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 

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM