Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IP address on GAE with Flask with ProxyFix

I have a Python 3 app on Google App Engine Standard.

I was using request.remote_addr to get users' IP addresses and it was always returning 127.0.0.1.

I then added werkzeug ProxyFix like this:

from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)

I'm also using other middleware to enable cloud ndb:

app.wsgi_app = ndb_wsgi_middleware(app.wsgi_app)

Now request.remote_addr always returns 169.254.1.1 which is a link-local IP address.

Is there a way to fix ProxyFix to get Flask to return the correct IP address?

The X-Forwarded-For header does have the right IP address, but I'd like to get this IP address in request.remote_addr.

like image 973
gaefan Avatar asked Sep 01 '25 03:09

gaefan


1 Answers

It looks like app engine has two proxies. Don't know what the second one is (one is for the load balancer).

The solution is to tell ProxyFix to trust both proxies, and you do that this way:

app.wsgi_app = ProxyFix(app.wsgi_app, x_for=2)
like image 60
gaefan Avatar answered Sep 02 '25 17:09

gaefan