在基于 Flask 的应用程序中获取客户端 IP

2023-12-14

我在服务器中部署了 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

有人可以在这里指导我吗?


Use 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在基于 Flask 的应用程序中获取客户端 IP 的相关文章

随机推荐