在python中保存配置文件的最佳做法

茶碱

我有一个python脚本,其中有一个配置文件,如下所示:

PROD = 'production'
DEV = 'dev'
ENVIRONMENT = None

我有一个函数可以从命令参数获取所需的环境并将其设置为:

if sys.argv[1] in [config.PROD, config.DEV]:
    config.ENVIRONMENT = sys.argv[1]

我了解当我开始将配置文件导入多个文件并且ENV一直重置为None时,这不是一个好习惯。

所以,我的问题是:这种情况的最佳实践是什么

J·达内尔

我不确定最好的做法是什么,但是我喜欢使用JSON文件。我将以下类用作与config(属性)文件接口的抽象层。您可以创建一个JSONPropertiesFile并将其传递给您的应用程序。

import json
from collections import OrderedDict
import os
from stat import * # ST_SIZE etc
from datetime import datetime
from copy import deepcopy


class JSONPropertiesFileError(Exception):
    pass


class JSONPropertiesFile(object):

    def __init__(self, file_path, default={}):
        self.file_path = file_path
        self._default_properties = default
        self._validate_file_path(file_path)

    def _validate_file_path(self, file_path):
        if not file_path.endswith(".json"):
            raise JSONPropertiesFileError(f"Must be a JSON file: {file_path}")
        if not os.path.exists(file_path):
            self.set(self._default_properties)

    def set(self, properties):
        new_properties = deepcopy(self._default_properties)
        new_properties.update(properties)
        with open(self.file_path, 'w') as file:
            json.dump(new_properties, file, indent=4)


    def get(self):
        properties = deepcopy(self._default_properties)
        with open(self.file_path) as file:
            properties.update(json.load(file, object_pairs_hook=OrderedDict))
        return properties

    def get_file_info(self):
        st = os.stat(self.file_path)
        res = {
            'size':st[ST_SIZE],
            'size_str':str(round(st[ST_SIZE]/1000,2)) + ' KB',
            'last_mod': datetime.fromtimestamp(st[ST_MTIME]).strftime("%Y-%m-%d")
         }
         return res

在您的情况下,您可以这样使用它:

file_path = "path/to/your/config/file"
default_properties = {
    'PROD': 'production',
    'DEV': 'dev',
    'ENVIRONMENT': ""
} 
config_file = JSONPropertiesFile(file_path, default_properties)
config = config_file.get() 
print(config["PROD"])
config["PROD"] = "something else"
config_file.set(config) #  save new config

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章