For example, I have a config json file that doesn’t need to modify at all, but views may need to read it:
Core_config:
{
"timeout":300,
"some_url":"https://(some url)"
.
.
.
}
My question is, where should I put the variable of the global data?
Option 1 : place at AppConfig:
#apps.py
class CoreAppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'Core'
config = None
def ready(self):
try:
with open(os.path.join(apps.get_app_config(self.name).path, self.name + '_config.json'), 'r', encoding='utf-8') as f:
config_str = f.read()
self.config = json.loads(config_str)
except Exception as e:
print('open ' + self.name + '_config.json failed')
#####################################################################
#views.py
def some_api(request):
some_url = apps.get_app_config("Core").config["some_url"]
.
.
.
I know it is not good for a view to access AppConfig directly, so I have another options:
Option 2 : place it at a new class:
#myconfig.py
class MyConfig:
core_config = None
#####################################################################
#apps.py
class CoreAppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'Core'
config = None
def ready(self):
try:
with open(os.path.join(apps.get_app_config(self.name).path, self.name + '_config.json'), 'r', encoding='utf-8') as f:
config_str = f.read()
MyConfig.core_config = json.loads(config_str)
except Exception as e:
print('open ' + self.name + '_config.json failed')
#####################################################################
#views.py
def some_api(request):
some_url = MyConfig.core_config["some_url"]
.
.
.
Which one is better? Or is there any better options other than the 2 options above?