Loading Django Settings for the Current Git Branch
A GitPython-based approach for detecting the active branch and loading its matching Django settings automatically.
Before deployment, I test the code and functionality against several separate databases so that local data is preserved while I verify the branch currently used in production.
As usual, the configuration is split into two files: settings.py provides the baseline, and settings_local.py overrides it. The latter is not tracked, so it can be changed freely.
Changing the configuration manually every time I switched branches was tedious. I wanted to load it automatically by detecting the current branch. There are two main Python libraries for working with Git, PyGit2 and GitPython. Their popularity was similar, so after briefly reviewing their documentation, I chose GitPython:
from git import Repo
git_repo_path = '/home/you_git_repo'repo = Repo(git_repo_path)if repo.active_branch.name == 'develop': conf = conf1else: conf = conf2You could also run git branch through Python’s os module and parse the output, but that is more cumbersome.