High response time when setting value for Django settings module inside a middleware

152 views Asked by At

In a Django project of mine, I've written a middleware that performs an operation for every app user.

I've noticed that the response time balloons up if I write the following at the start of the middleware module:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE","myproject.settings")

It's about 10 times less if I omit these lines. Being a beginner, I'm trying to clarify why there's such a large differential between the respective response times. Can an expert explain it? Have you seen something like it before?


p.s. I already know why I shouldn't modify the environment variable for Django settings inside a middleware, so don't worry about that.

1

There are 1 answers

1
2ps On BEST ANSWER

The reason will likely have to do something with django reloading your settings configuration for every request rather than once per server thread/process (and thus, also, re-instantiating/connecting to your database, cache, etc.). You will want to confirm this with profiling. this behavior is also very likely dependent on which app server you are running.

If you really want this level of control for your settings, it is much easier for you to add this line to manage.py, wsgi.py or whatever file/script you use to launch your app server.

P.S. If you already know you shouldn’t do it, why are you doing it?