1

我在服务器中部署了 Flask 应用程序。我们正在使用 Nginx。nginx设置如下:

proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_read_timeout 25s;
proxy_pass http://127.0.0.1:8000;
add_header X-Cache $upstream_cache_status;

在 Flask 设置中,我完成了以下操作:

app = Flask(__name__, static_folder=None)
app.wsgi_app = ProxyFix(app.wsgi_app)

现在,每当用户访问网站时,我都想要一个真实的 ip。目前我得到

127.0.0.1

我试过如下:

if request.headers.getlist("X-Forwarded-For"):
    ip = request.environ['HTTP_X_FORWARDED_FOR']
else:
    ip = request.remote_addr

任何人都可以在这里指导我。

4

2 回答 2

3

利用request.access_route

https://github.com/pallets/werkzeug/blob/master/werkzeug/wrappers.py

@cached_property
def access_route(self):
    """If a forwarded header exists this is a list of all ip addresses
    from the client ip to the last proxy server.
    """
    if 'HTTP_X_FORWARDED_FOR' in self.environ:
        addr = self.environ['HTTP_X_FORWARDED_FOR'].split(',')
        return self.list_storage_class([x.strip() for x in addr])
    elif 'REMOTE_ADDR' in self.environ:
        return self.list_storage_class([self.environ['REMOTE_ADDR']])
    return self.list_storage_class()

示例 Nginx 配置:

location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Protocol https;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_redirect off;
        proxy_pass http://127.0.0.1:9000;
}
于 2018-03-01T15:19:07.610 回答
0

你应该有:

ip = request.access_route[-1]
于 2021-09-27T15:01:24.283 回答