Using same config file in multiple scripts/modules

66 Views Asked by At

Hello I develop a web app with Flask, I use a config file (config.ini) with the ConfigParser library.

I want to factorize the code, because I need to use the same config.ini file in multiples scripts and modules. I've thinked to create a config.py module that load the config file (this code is working) and then import this module where it's needed.

#config.py
import pathlib
import configparser

#To load config file
def loadConfig(): 
    # To get absolute path of file config.ini (useful when deployed) 
    config_path = pathlib.Path(file).parent.absolute() / "config.ini" 
    # Loading ConfigParser to read context from config file : Value = [Section][Key] 
    configData = configparser.ConfigParser() 
    return configData.read(config_path)

Then I try to use this module like this :

#views.py
from Project.modules import config

configData = config.loadConfig()

print (configData['Section']['Key']) #got an error here, section and key exists in config.ini

Error I get : list indices must be integers or slices, not str

If I put the code from config.py into views.py it works well , but it means that I have to put this code in every .py files that need to load config data.

How to perform this correctly ?

Thanks

1

There are 1 best solutions below

0
Mayot On

after 1hour of debuging I finaly get my point : I wasn't on the config file...

I've done some slightly change in my code. Here is the project :

-Project
---modules
------__init__.py
------config.py
---config.ini
---views.py

The config.py file

#config.py    
import pathlib
import configparser

# To get absolute path of file config.ini (useful when deployed)
config_path = pathlib.Path(__file__).parent.parent.absolute() / "config.ini"

# Loading ConfigParser to read context from config file : Value = [Section][Key]
configData = configparser.ConfigParser()
configData.read(config_path)

#To load config file
def loadConfig():
    return configData

Then

from Project.modules import config 
# Loading ConfigParser to read context from config file : Value = [Section][Key]
configData = config.loadConfig()


UPLOAD_FOLDER = configData['Folder']['folderRoot']

Everything is working as I wanted