Search code examples
pythonpyyaml

Read YAML configuration file in Python


I am trying to read a YAML configuration file and display it to the terminal. Now I want to try something like checking if the database (db) in the YAML file is not Sqlite or Postgres then exception will raise but I don't know how. I tried but failed, what am I doing wrong?

My test.yaml file :

database: 

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

query:
   select * from manufacturing_product

My code:

# process_yaml.py file`
import yaml

with open(r'D:\Python\test.yaml') as file:
    # The FullLoader parameter handles the conversion from YAML
    # scalar values to Python the dictionary format
    data = yaml.full_load(file)

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

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

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

My program still cannot catch the exception. My terminal :

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

Solution

  • There are several pieces missing from your code, and your function __init__ is never called. You probably copied it from some example with a class, that also had a method get_db_type().

    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
    
        def get_db_type(self):
            return self._dbconf['db']
    
    
    with open('test.yaml') as file:
        data = yaml.full_load(file)
    
        for item, doc in data.items():
            print(item, ":", doc)
    
    
        db = DB(data)
    

    Which prints:

    db : mysql
    dbopt : {'host': 'bvcbvcbvcb.com', 'port': 5432, 'dbname': 'db1', 'user': 'username', 'password': '1234', 'client_encoding': 'utf-8', 'connect_timeout': 60, 'sslmode': 'none'}
    query : select * from manufacturing_product
    

    and then gives:

    init raise InvalidConfigError( main.InvalidConfigError: ('E01001', 'Invalid database type, should be sqlite or postgres.') process error Command '['ryd', '--force', 'so-60160957.ryd']' returned non-zero exit status 1.

    The comment

    # The FullLoader parameter handles the conversion from YAML
    # scalar values to Python the dictionary format
    

    is rather of the mark. The FullLoader parses the YAML and tries to instantiate all nodes into Python objects: YAML mapping to dict, YAML sequence to list, and YAML nodes that are scalars to Python types (string, integer, float, bool, etc.)