From Novice to Expert: How to Write a Configuration file in Python
W hen we design software, we normally put a lot of effort into writing high-quality code. But that’s not enough. Good software should also take care of its eco-system, like testing, deployment, network, etc. One of the most important aspects is configuration management.
Good configuration management should allow the software to be executed in any environment without changing the code. It helps Ops to manage all the hassle settings and it provides a view of what can happen during the process and even allows them to change the behavior during the runtime.
The most common configuration includes credentials to the database or an external service, the hostname of the deployed server, dynamic parameters, etc.
In this article, I want to share with you some good practices of configuration management and how we can implement them in Python. If you have more ideas, please leave your comments below.
When do we need a separate configuration file?
Before writing any configuration file, we should ask ourselves why we need an external file. Can’t we just make them constants in the code? Actually, the famous The Twelve-Factor App has answered this question for us:
A litmus test for whether an app has all config correctly factored out of the code is whether the codebase could be made open source at any moment, without compromising any credentials. Note that this definition of “config” does not include internal application config, such as config/routes.rb in Rails, or how code modules are connected in Spring. This type of config does not vary between deploys, and so is best done in the code.
It recommends that any environment-dependent parameters such as database credentials should sit in the external file. Otherwise, they are just normal constants in the code. Another use case I see a lot is to store dynamic variables in the external file, for instance, a blacklist or whitelist. But it can also be a number within a certain range (e.g. timeout) or some free texts. These variables can possibly be the same in each environment, but the configuration file…
Python config best practice
А вот JSON-представление: