首页 > 解决方案 > 部署后如何集成配置文件?

问题描述

我有以下文件夹结构:

    helloworld /
    │
    ├── helloworld.py
    ├── conf.json
    ├── setup.py
    ├── parameterManager.py

该功能非常基本 - 我的 helloworld.py 从 conf.json 读取参数并打印它:

    from parameterManger import return_params as pm
    what_to_print = pm("print")
    print(what_to_print)

我的 parameterManager.py 帮助我读取 json 如下:

import os
import josn
def return_params (ParameterName=None, conf_file_name='/conf.json',):
    try:
        ConfFolder = os.path.dirname(__file__)
        ConfFile=ConfFolder + conf_file_name
        with open(ConfFile) as json_data_file:
            Data = json.load(json_data_file)
            if ParameterName is None:
                return Data
            ParamterValue=Data[ParameterName]
            return ParamterValue
    except Exception as e:
        print(e)

在我“部署”之前它工作得很好

在另一个项目中我 git+ http://gitlab.lan/username/helloworld.git 但我总是得到错误

'NoneType' object is not subscriptable
[Errno 2] No such file or directory: 'D:\\path_to_new_project\\venv\\lib\\site-packages\\conf.json'

我可以考虑“肮脏”的解决方案,但我 100% 确定有一种“pythonic”方式可以在项目之间共享文件。有人可以与我分享正确的做法吗?

标签: jsonpython-3.xconfigurationconfig

解决方案


首先,我认为你应该打包helloworld成一个包,比如:

helloworld
├── helloworld
│   ├── __init__.py
│   ├── config.json
│   ├── helloworld.py
│   └── parameterManager.py
└── setup.py

然后,添加config.json到您的package_datain setup.py

from setuptools import setup

...

PACKAGES = [
  'helloworld'
]

PACKAGE_DATA = {
  'helloworld' : ['config.json']
}

...

setup(
    ...
    packages=PACKAGES,
    package_data=PACKAGE_DATA,
    ...
)

推荐阅读