Django + mod_wsgi. Set OS environment variable from Apache SetEnv

I need to separate the development and production settings of Django. I decided that if the USKOVTASK_PROD variable USKOVTASK_PROD set, the application should use the production settings. I read this article and tried to do it.

My snippets:

/etc/apache2/sites-enabled/uskovtask.conf:

 <VirtualHost *:80> ServerName uskovtask.*.com ServerAlias uskovtask.*.com DocumentRoot /mnt/ebs/uskovtask Alias /static /mnt/ebs/uskovtask/static/ <Directory /mnt/ebs/uskovtask/static> Require all granted </Directory> #WSGIPythonPath /mnt/ebs/uskovtask WSGIDaemonProcess uskovtask.*.com python-path=/mnt/ebs/uskovtask:/usr/lib/python2.7/site-packages WSGIProcessGroup uskovtask.*.com WSGIScriptAlias / /mnt/ebs/uskovtask/uskovtask/wsgi.py SetEnv USKOVTASK_PROD 1 <Directory /mnt/ebs/uskovtask/uskovtask> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> 

wsgi.py:

 import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "uskovtask.settings") from django.core.wsgi import get_wsgi_application _application = get_wsgi_application() def application(environ, start_response): if 'USKOVTASK_PROD' in environ: os.environ.setdefault('USKOVTASK_PROD', environ['USKOVTASK_PROD']) return _application(environ, start_response) 

settings.py parameter:

 import os if 'USKOVTASK_PROD' in os.environ: from settings_prod import * else: from settings_dev import * 

But it always imports settings_dev parameters. Why?

+6
source share
2 answers

This is due to the issue of accessing the Apache SetEnv variable from the Django wsgi.py file

You need to inherit WSGIHandler as the answer says.

As Graham Dumpleton says in the second answer,

With all that said, the blog post you mentioned will usually not help. This is because it uses the unpleasant trick of setting up process environment variables for each request based on the WSGI request environment settings set using SetEnv in Apache. This can cause various problems in a multi-thread configuration if the values ​​of the environment variables may differ depending on the context of the URL. For the Django case, this is not useful because the Django settings module is usually imported before any requests are processed, which means that the environment variables will not be available at the time required.

and I think this is what happens in your case.

+4
source

I solved this problem by changing wsgi.py to this:

 from django.core.handlers.wsgi import WSGIHandler import django import os class WSGIEnvironment(WSGIHandler): def __call__(self, environ, start_response): os.environ['USKOVTASK_PROD'] = environ['USKOVTASK_PROD'] os.environ.setdefault("DJANGO_SETTINGS_MODULE", "uskovtask.settings") django.setup() return super(WSGIEnvironment, self).__call__(environ, start_response) application = WSGIEnvironment() 
+6
source

Source: https://habr.com/ru/post/978293/


All Articles