如何做好python项目的配置分离

2019-07-24  本文已影响0人  一百万个不确定

本文内容:

项目配置分离

配置合并

分离

为什么要分离:

为区分正式和开发而分离

为了隔离敏感信息而分离

为了方便程序员写代码而分离

如何做分离

代码目录结构

config/
    __init__.py
    common.yml
    dev.yml
    prod.yml

存放开发环境配置

db:
  {
    SQLALCHEMY_DATABASE_URI: "mysql+pymysql://admin@localhost:3306/test?charset=utf8mb4"
  }
export database_password="hello"

合并

合并的代码:

import os
import yaml
env = os.environ.get('env', 'dev')


def load_env(env_file_name):
    file = open(os.path.join(os.path.dirname(__file__), env_file_name), 'r', encoding='utf-8')
    cfg = yaml.safe_load(file)
    return cfg


def merge_conf(base, to_be_merged):
    for i in to_be_merged.keys():
        base[i] = to_be_merged[i]
    return base


def load_env_outside():
    env_conf = dict()
    env_conf['database_password'] = os.environ.get('database_password')
    return env_conf


CONF = load_env('common.yml')

if env == 'dev':
    dev_conf = load_env('dev.yml')
    CONF = merge_conf(CONF, dev_conf)
elif env == 'prod':
    prod_conf = load_env('prod.yml')
    CONF = merge_conf(CONF, prod_conf)
    env_outside = load_env_outside()
    CONF = merge_conf(CONF, env_outside)
else:
    raise EnvironmentError('Environment error')

print(CONF)

执行结果

{'authorize': {'token': 'justtoken', 'expire_time': 1200, 'reset_password_expire_time': 2400}, 'date_format': '%Y-%m-%d %H:%M:%S', 'db': {'SQLALCHEMY_DATABASE_URI': 'mysql+pymysql://admin@xxx:3306/prod?charset=utf8mb4'}, 'database_password': 'hello'}
上一篇下一篇

猜你喜欢

热点阅读