Learning Django Source Code - Configuration File Parsing
I’ve been using Django for several years. During this period, I’ve looked at a little bit of the source code from time to time due to project development needs, but I’ve never looked at the source code as a whole. Recently, I found a good tutorial on explaining the Django source code on Bilibili, Shen Qicai · Django 4.0 Source Code Interpretation. I plan to go through it following this video. However, for the latest code I’ve seen, I forked a copy of the code from the official Django repository, yexia553/django. Later, I will submit relevant annotations and explanations on the learning branch of this repository.
I don’t plan to explain the code line by line. I will only record some content that I think is well-written or helpful for me to understand the design of Django.
This blog will record the code related to django.conf.settings, that is, the part related to project configuration in Django.
global_settings
This part of the code is located in django.conf.global_settings. To be honest, I didn’t know there was such a piece of code in Django before.
django.conf.global_settings contains more comprehensive configuration items compared to django.conf.settings and is also the basis of django.conf.settings.
settings
The configuration of Django is referenced in the code as follows:
1 | from django.conf import setting |
The actual code is located in the file django.conf.__init__.py
Here is part of the code of the Settings class:
1 | class Settings: |
Pay main attention to the two lines of code setattr(self, setting, getattr(global_settings, setting))
and mod = importlib.import_module(self.SETTINGS_MODULE)
.
setattr(self, setting, getattr(global_settings, setting))
uses the magic function setattr to dynamically set attributes for the Settings class. This design allows us to customize configurations in the settings.py file of a Django project and have them loaded by Django.
The function of mod = importlib.import_module(self.SETTINGS_MODULE)
is to dynamically (at runtime) import modules. This is very useful when we don’t know which specific module will be used when writing the program, but it is determined at runtime by user input or other means.
The self.SETTINGS_MODULE
is the value of the DJANGO_SETTINGS_MODULE environment variable. It is precisely because of this design that we can change the default settings.py file created when creating a project into multiple files such as prod/settings.py and testing/settings.py written according to different running environments.
Imagine if we didn’t use dynamic import here but hard - coded it, we would be troubled by how to adapt to different environments.