Manage python project configurations
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:
base_config.py
1 | #!/usr/bin/env python |
config_dev.py
1 | #!/usr/bin/env python |
config_prod.py
1 | #!/usr/bin/env python |
config.py
1 | #!/usr/bin/env python |
init.py
this file is only to declare: the costconfig is a module
from other file
1 | 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=production
to 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 -e
to edit the crontab and addMY_ENV=production
at the first line.
Reference:
Better Cron env and shell control with the SHELL variable
Scheduling Cron Jobs with Crontab
how-can-i-run-a-cron-command-with-existing-environmental-variables
Author: d0zingcat
Link: https://infloop.life/2019/05/03/manage-python-configs/
License: 知识共享署名-非商业性使用 4.0 国际许可协议