Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read UWSGI parameters in python/flask passed from nginx

I set up python/flask/uwsgi+nginx web app and it works fine. I want to use geoip, I set it up on nginx side:

   location / {
            include         uwsgi_params;
            uwsgi_pass      unix:/tmp/qbaka-visit.sock;
            ...
            uwsgi_param     GEOIP_COUNTRY_CODE $geoip_country_code;
    }

But now I don't know how to read this property in python. Prior to uwsgi I used simple flask builtin webserver + nginx proxy_pass, in which case I used proxy_set_header X-Geo-Country $geoip_country_code; and read this argument using request.headers, but for UWSGI params I couldn't figure out how to read them.

like image 755
Daniil Avatar asked Jan 03 '13 05:01

Daniil


People also ask

How does Nginx uWSGI work?

Nginx implements a uwsgi proxying mechanism, which is a fast binary protocol that uWSGI can use to talk with other servers. The uwsgi protocol is actually uWSGI's default protocol, so simply by omitting a protocol specification, it will fall back to uwsgi . Save and close the file when you are finished.


1 Answers

uwsgi_param sets a wsgi environ key of the given name to the application. You can use this for headers, which follow the CGI convention of using an HTTP_ prefix. the equivalent of your proxy_set_header would be:

uwsgi_param HTTP_X_GEOIP_COUNTRY $geoip_country_code;

note that the header name must be in upper case and with dashes replaced by underscores, to be recognized as a valid header in wsgi.

Alternativly, it looks like the environ is accessible in flask, as request.environ, so you could keep your uwsgi_param the same, but read it as request.environ['GEOIP_COUNTRY_CODE']. This is probably preferable, actually, since you can distinguish them from actual request headers that way.

like image 53
SingleNegationElimination Avatar answered Oct 31 '22 01:10

SingleNegationElimination