为什么在使用 Python 的 configparser 读取 ini 文件时出现 KeyError?

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

我想连接到 Python 中的数据库。 我的代码:

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()

我的 config.ini 看起来像这样:

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

但是我得到一个错误KeyError: 'user'。这是什么意思?该用户不存在?

整个追溯:

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'

您需要首先从配置中访问 books 部分:

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()