【问题标题】:How to integrate config files after deploy?部署后如何集成配置文件?
【发布时间】:2020-01-03 12:54:59
【问题描述】:

我有以下文件夹结构:

    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”方式可以在项目之间共享文件。有人可以与我分享正确的做法吗?

【问题讨论】:

  • 你如何“部署”它?您能提供更多信息吗?
  • 在部署中我的意思是 - 与我的团队/同事以一种他们可以“pip install helloworld”的方式共享项目(不是以 pypi 方式,而是通过 git)。这就是 setup.py 的原因

标签: json python-3.x configuration config


【解决方案1】:

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

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

然后,将config.json 添加到package_data 中的setup.py

from setuptools import setup

...

PACKAGES = [
  'helloworld'
]

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

...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多