Search code examples
pythoniniconfigparser

Why am I getting a KeyError when reading an ini file with Python's configparser?


I would like to connect to the database in Python. My code:

from configparser import ConfigParser
import pymysql as mysql

class DatabaseG:
    def __init__(self):
        config = ConfigParser()
        config.read("config.ini")
        self.connection = mysql.connect(
                user=config["books"]["user"],
                passwd=config["books"]["password"],
                host=config["books"]["host"],
                db=config["books"]["database"],
        )
        self.cursor = self.connection.cursor()
        query = """
                CREATE TABLE BOOKS (book_url TEXT, book_id)
                """

        self.cursor.execute(query)

db = DatabaseG()

My config.ini looks like this:

[books]
user=myuser
password=mypass
host=blabla.cz
database=

But I got an error KeyError: 'user'. What does it mean? The user does not exist?

Whole Traceback:

Traceback (most recent call last):
  File "<input>", line 259, in <module>
  File "<input>", line 205, in main
  File "/home/vojtam/Desktop/mydb/db.py", line 25, in __init__
    user=config["books"]["user"],
  File "/usr/lib/python3.8/configparser.py", line 960, in __getitem__
    raise KeyError(key)
KeyError: 'user'

Solution

  • You need to access the books section first from the config:

    from configparser import ConfigParser
    import pymysql as mysql
    
    class DatabaseG:
        def __init__(self):
            config = ConfigParser()
            config.read("config.ini")
            books_config = config["books"]
            self.connection = mysql.connect(
                    user=books_config["user"],
                    passwd=books_config["password"],
                    host=books_config["host"],
                    db=books_config["database"],
            )
            self.cursor = self.connection.cursor()
            query = """
                    CREATE TABLE BOOKS (book_url TEXT, book_id)
                    """
    
            self.cursor.execute(query)
    
    db = DatabaseG()