When working on a python project I’ve been thinking how to manage the configurations in an elegant way, just like the ‘maven-way’(use a placeholder and replace them when packaging). Here are some points I care about:
- separate development and production configs
- easy to use, no need to include third party packages
- safe, will not be committed to git repo by mistake
- out-of-box, no need to modify the code to run on production or development environment
As I have such requirements, after researching I finally choose this way to handle it.
The structure looks like:
this file is only to declare: the costconfig is a module
from other file
from costconfig.config import config as Config
In the files you need to use config you just need to import it.
As you can see, the config file is key point. When entering the main scope, it will try to get environment ‘MY_ENV’(‘default’ by default and will use dev config) and get related config class according to this env variable, by which we can easily export an environment ‘MY_ENV’ to production on the server then the program will use production config. In this way, we can just run the same code without modifying even one line of the codes on server or on local development environment, just modify the configs and everything works fine.
In addition, there are still three steps you have to take.
- add this filename into .gitignore, for me is:
*config/*_prod.*to ignore the production config, in this case we will never have to worry about commit the production config to git repo(e.g. Github)
- export MY_ENV on server, for me is add
export MY_ENV=productionto the end of ~/.bshrc
- if you use a crontab to execute your script, you will find the program fails. That’s because the crontab env is not safe like your bash, namely it will not execute your ~/.bashrc file first before executing. So, you have to declare in the crontab, just use
crontab -eto edit the crontab and add
MY_ENV=productionat the first line.
License: 知识共享署名-非商业性使用 4.0 国际许可协议