Meet Gondaliya
Meet Gondaliya

Reputation: 435

How to get data from config file (config.json) in real time in settings.py file in django

I have a project made in Django. I have only added social auth for login purposes. I want selected emails only to log in to the website. I used social-auth-app-django library for social auth and added a variable SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_EMAILS to the settings.py file where it contains a list of all the emails permitted for logging in.

My project directory looks something like this:

project_parent/
----project/
--------settings.py
--------wsgi.py
--------asgi.py
--------urls.py
----app/
--------models.py
--------views.py
--------urls.py
--------admin.py
----db.sqlite3
----manage.py
----config.json

Here is the config file:

{
    "OAUTH2": {
        "WHITELISTED_EMAILS": [
            "[email protected]",
            "[email protected]", 
            "[email protected]", 
            "[email protected]"
        ]
    }
}

In settings.py file I have loaded the config file like this:

config = open('./config.json',)
data = json.load(config)
SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_EMAILS = data['OAUTH2']['WHITELISTED_EMAILS']

I have made a webpage that takes the new mail id (need to add to the config file) and appends that particular mail id (or a list of mail ids) to the config.json file. But now the problem arises, the newly added mails don't reflect directly to the variable defined in the settings.py file. For that, I need to restart the code in order to get the latest config file. Every time I add a mail id, I need to restart the code.

I thought to make a database table in my app folder and load that table in settings.py by import the model from app folder. But on importing, the terminal raises the error as it says app is still not loaded so that I can't use the models inside my app.

Is there a way in which I can directly load the database table without importing the models.py file from app folder? Or if possible to load the config.json file in real-time so that I don't have to restart the code

Upvotes: 1

Views: 2397

Answers (1)

Akash
Akash

Reputation: 117

settings.py in Django is loaded once at execution time, we should not change the values during runtime. Although that is suggested by the docs there are ways you can change the settings values during runtime. You can use django-constance library, and then make a form to update the setting's value during runtime by editing the database value.

Upvotes: 1

Related Questions