Forums

ConfigParser Not Reading Config?

I have an issue where I'm getting

2021-12-31 19:42:34,208: Error running WSGI application
2021-12-31 19:42:34,215: KeyError: 'database'

I'm using Python's configparser library to fetch and load config.ini. The app and the config file are in the same directory. This is working correctly on my local machine. It is also working correctly from a console running in the same directory as my app and config file.

import configparser
config = configparser.ConfigParser()
config.read("config.ini")
hostname = config["database"]["hostname"] # <-- this line throws the error

If I put those same lines into a console running in the same directory as my app and the config files, it works. But when it runs from my app, I get the KeyError mentioned above.

This first felt like a permissions issue, so I kicked the doors open with a chmod 777 config.ini, reloaded my app, tested, same KeyError.

Since configparser will just give you an empty config if the file isn't found or can't be read, I'm at a loss for how to dig into this more.

I'd love any crackpot ideas anyone might have about this. Clearly there's something for me to learn here, I'm just not catching on.

EDIT - I decided to try to generate the config.ini file using configparser to actually write the sections and add values and such. The file was written but the app still doesn't read it. The only other idea I have at this point is to modify my app to write the config file when it starts up just to see if that solves the problem (maybe whatever user the app runs as would then own it and could read it?), but that won't work long term for what are probably obvious reasons.

Back to the drawing board.

What config.sections() returns? Maybe add some logging to inspect that object.

Thanks for the reply. config.sections() gives an empty list when done from the app. When done from the Python console manually, I get sections.

I decided to add some code to attempt to open the file for reading to see what happens...

print("xyzzy 1")
with open("config.ini", "r") as cfile:
    for line in cfile.readlines():
        print(line)
print("xyzzy 2")

And wouldn't you know it? File not found. So I figured maybe the relative path isn't working from the app for some reason. Swapped it to the full path and it works.

So now I'm wondering why the relative path isn't working from the app but it does from the console. Thoughts?

Log os.getcwd() and you will see.

I expected the working directory to be the same as the location of my code, hence the confusion.

I solved this by using pathlib to find the absolute path to my app and append "config.ini" to the end. This way it works locally and remote.

import pathlib
import configparser

config_path = pathlib.Path(__file__).parent.absolute() / "config.ini"
config = configparser.ConfigParser()
config.read(config_path)

Working fine now. Guess I should have checked the working directory since my intuition was obviously wrong.