在多个脚本/模块中使用相同的配置文件

问题描述 投票:0回答:1

您好,我使用 Flask 开发一个 Web 应用程序,我使用带有 ConfigParser 库的配置文件 (config.ini)。

我想分解代码,因为我需要在多个脚本和模块中使用相同的 config.ini 文件。我想创建一个 config.py 模块来加载配置文件(此代码正在运行),然后在需要的地方导入此模块。

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

然后我尝试像这样使用这个模块:

#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

我得到的错误:列表索引必须是整数或切片,而不是 str

如果我将 config.py 中的代码放入views.py 中,效果很好,但这意味着我必须将此代码放入每个需要加载配置数据的 .py 文件中。

如何正确执行此操作?

谢谢

python module configparser
1个回答
0
投票

经过 1 小时的调试,我终于明白了我的意思: 我不在配置文件中...

我对我的代码做了一些细微的改变。这是项目:

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

config.py 文件

#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

然后

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


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

一切都如我所愿

© www.soinside.com 2019 - 2024. All rights reserved.