Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic configuration in Django

I am trying to have some configuration settings in Django be automatically determined at runtime.

I have set up a middleware handler that runs once, before the first request is made, and then disables itself by raising MiddlewareNotUsed. When the handler runs, it pulls some information from another server via HTTP. I would like to have that information become available for use in all views.

In the settings module, I have an empty string. I thought that I would be able to dynamically modify this with the retrieved information, so that it would become available to all the views. But when I update the string from the middleware handler, the information is somehow lost. The views see only the empty string.

How would I make the information that was retrieved over HTTP available to all the views?

I would like to keep it in memory, not in a database or on the filesystem, though I will use one of those options if that is the only choice.

like image 940
Roger Dahl Avatar asked May 04 '26 06:05

Roger Dahl


1 Answers

Ok, I did something similar once and I'm not very proud of it :)

But it's quite simple and did the job, so here it is:

from django.conf import settings

class SomeMiddleware(object):
    def process_request(self, request):
        try:
            settings.SOME_STRING_CONFIG
        except AttributeError:
            settings.SOME_STRING_CONFIG = some_value_to_set

However, this is not a nice way to treat django.settings, see https://docs.djangoproject.com/en/dev/topics/settings/#altering-settings-at-runtime.

No, let me quote it here:

Altering settings at runtime
You shouldn't alter settings in your applications at runtime. For example, don't do this in a view:

from django.conf import settings
settings.DEBUG = True # Don't do this!

The only place you should assign to settings is in a settings file.

(I added the bold)

like image 160
frnhr Avatar answered May 05 '26 19:05

frnhr