Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Flask WSGI file is ignoring user's environment variables

I have configured Apache on Ubuntu 12.04 to run my Python Flask web application using WSGI. Here is part of /etc/apache2/sites-enabled/000-default:

<VirtualHost *>
    WSGIDaemonProcess 3dkit user=3dkit group=3dkit threads=5
    WSGIScriptAlias /3dkit /3dkit/kit.wsgi
    WSGIPassAuthorization On

    <Location /3dkit>
    WSGIProcessGroup 3dkit
    </Location>
...

And here is /3dkit/kit.wsgi:

import os
import sys

sys.path.insert(0, '/3dkit')
print 'user =', os.environ['USER']

from kit import app as application

The print command fails with the exception

KeyError: 'USER'

Yet this command in the terminal window:

sudo -u 3dkit printenv USER

outputs "3dkit" as expected.

It's not just this environment variable. No matter how I try to set an environment variable, whether in /home/3dkit/.profile, or in /etc/environment, or any other way I can think of, it is ignored in my WSGI file. The only way I can make it work is to explicitly call os.environ and set an environment variable in the WSGI file itself.

Can anyone tell me what I'm doing wrong?

like image 731
Steve Saporta Avatar asked May 01 '26 21:05

Steve Saporta


1 Answers

The WSGI daemon process runs in a very santizied environment, and the only variables set are PATH and LANG. (And in my case, NOTIFY_SOCKET, since Apache is started by systemd). USER, SHELL, and all the other variables you see in an interactive shell are not set, and the shell initialization files (.profile, etc) aren't run.

Are you using USER as an example, or do you actually want to identify the owner of the process? os.getuid() and friends will return the uid, and you can convert it into the username with something like pwd.getpwuid(os.getuid())[0] (see the pwd and os modules).

If what you actually want is to access typical server environment variables one might see in a CGI script (e.g. HTTP_REFERER, REMOTE_ADDR, etc), those are in the server environment, which in Flask is accessible via Werkzeug's Request object, which is available with, e.g. from flask import Flask, request. You can then access, e.g. request.environ['HTTP_REFERER']

like image 85
jdreed Avatar answered May 04 '26 10:05

jdreed