json - 部署后如何集成配置文件?
问题描述
我有以下文件夹结构:
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”方式可以在项目之间共享文件。有人可以与我分享正确的做法吗?
解决方案
首先,我认为你应该打包helloworld
成一个包,比如:
helloworld
├── helloworld
│ ├── __init__.py
│ ├── config.json
│ ├── helloworld.py
│ └── parameterManager.py
└── setup.py
然后,添加config.json
到您的package_data
in setup.py
。
from setuptools import setup
...
PACKAGES = [
'helloworld'
]
PACKAGE_DATA = {
'helloworld' : ['config.json']
}
...
setup(
...
packages=PACKAGES,
package_data=PACKAGE_DATA,
...
)
推荐阅读
- python - Django - 显示正确的变量
- javascript - js中像素颜色的OpenWeatherMap温度值
- r - 有没有办法将某些特定列转换为数字?
- javascript - NodeJS - mssql - 录制期间的土耳其语字符问题
- c - 未定义对“sqrt”的引用,但仅在使用变量时且仅在 CodeBlocks 中
- javascript - 无法在 Mapbox React 地图中渲染地图标记
- ssh - 在 gcp 实例上使用 Ansible 连接到另一个实例错误
- flutter - Flutter:连续调整两个文本子项的大小
- python - 如何将列表打印到单独的列表中python
- django - 如何处理 django 视图中的错误?