importcfg4py# create config objectcfg=cfg4py.init(path_to_config_dir)# then refer to settings by cfg's properties# given the following yaml settings (filename: defaults.yaml) under path_to_config_dir# services:# redis:# host: localhost# you can access settings by '.'print(cfg.services.redis.host)# you CANNOT access settings like this way (this will raise exceptions):print(cfg["services"])
Build config class, and import it into your project:
1
cfg4py build /path/to/your/config/dir
1 2 3 4 5 6 7 8 910
fromtypingimportTYPE_CHECKINGifTYPE_CHECKING:# make sure that schema is at your $PYTHONPATHfromschemaimportConfigimportcfg4pycfg:Config=cfg4py.init('/path/to/your/config/dir')# now you should be able to get auto-complete hint while typingcfg.?
cfg4py will take care of setting's change automatically, all you need to do is put correct settings into one of
(defaults, dev, test, production) config file. And once you change the settings, it should take effect immediately.
To enable cascading config, you can configure a remote source by implemented a subclass of RemoteConfigFetcher. A redis fetcher is provided out-of-box:
1234567
fromcfg4pyimportRedisConfigFetcherfromredisimportStrictRediscfg=cfg4py.int()# since we're using remote config now, so we can omit path param herefetcher=RedisConfigFetcher(key="my_app_config")logger.info("configuring a remote fetcher")cfg4py.config_remote_fetcher(fetcher,1)
The settings in redis under key should be a json string, which can be converted into a dict object.
Before starting run your application, you should set cfg4py_server_role to any of [DEV,TEST,PRODUCTION] (since 0.9.0, required only if you specified as strict mode). You can run the following command to get the help:
1
cfg4py hint set_server_role
Info
1
since 0.9.0, you can skip this step, if you don't need adaptive deployment support.
cfg4py does more than a config module, it can be a cheat sheet for many configurations. For example, want to change pip source (usually you'll if you're in china mainland):
1234567
cfg4py hint pip > - tsinghua: pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple - aliyun: pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ - tencent: pip config set global.index-url http://mirrors.cloud.tencent.com/pypi/simple - douban: pip config set global.index-url http://pypi.douban.com/simple/
for more, explore by yourself by typing cfg4py hint