Python Forum

Full Version: Read Yaml configuration file in Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I wrote a program 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
Quote: Invalid database type, should be sqlite or postgres
. I tried but still couldn't catch the exception. Can anyone give me suggestion?
My test.yaml file :
Quote:db: mysql
dbopt:
host: foobar.baz.qux.com
port: 6311
dbname: spam_eggs
user: hamburger
password: example_password
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 :
Output:
db : mysql dbopt : {'host': 'foobar.baz.qux.com', 'port': 6311, 'dbname': 'spam_eggs', 'user': 'hamburger', 'password': 'example_password', 'client_encoding': 'utf-8', 'connect_timeout': 60, 'sslmode': 'none'} query : select * from manufacturing_product
Is that all your code? Some things I notice:

- You have declared an __init__ function outside of a class. Why?
- Said function isn't actually called anywhere.
- There's no code to catch any exceptions.