title: Gunicorn Environment Variable Setting
body: <p>I'm currently having difficulty passing environment variables into Gunicorn for my Django project. I'm on the latest 19.1 version. I have a wsgi.py file like so:</p>
  
  <pre><code>import os
  import sys
  from django.core.wsgi import get_wsgi_application
  
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  PROJECT_DIR = os.path.abspath(os.path.join(BASE_DIR, '..'))
  
  sys.path.append(PROJECT_DIR)
  os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
  
  def application(environ, start_response):
      _application = get_wsgi_application()
      os.environ['SERVER_ENV'] = environ['SERVER_ENV']
      os.environ['SERVER_ID'] = environ['SERVER_ID']
      return _application(environ, start_response)
  </code></pre>
  
  <p>When I run gunicorn from the command line as:</p>
  
  <pre><code>SERVER_ENV=TEST SERVER_ID=TEST gunicorn -b 127.0.0.1:8080 --error-logfile - --access-logfile - app.wsgi:application
  </code></pre>
  
  <p>and I then pass a request to gunicorn I keep getting:</p>
  
  <pre><code>2014-08-01 08:39:17 [21462] [ERROR] Error handling request
  Traceback (most recent call last):
    File "/opt/virtualenv/python-2.7.5/django-1.5.5/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 93, in handle
      self.handle_request(listener, req, client, addr)
    File "/opt/virtualenv/python-2.7.5/django-1.5.5/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 134, in handle_request
      respiter = self.wsgi(environ, resp.start_response)
    File "/opt/sites/itracker/wsgi.py", line 18, in application
      os.environ['SERVER_ENV'] = environ['SERVER_ENV']
  KeyError: 'SERVER_ENV'
  </code></pre>
  
  <p>Printing out the environ values confirms that the environment variables are not being passed in. I've tried setting the environment variables in the virtualenv activation script and also in a dedicated gunicorn shell script and also by setting the environment variables using the --env flag but nothing seems to work.</p>
  
  <p>Any ideas?</p>