Flask:如何获取请求的客户端IP地址?

时间:2020-10-16 00:59:15

标签: python flask proxy request ip-address

问题:

大家好-我基本上是在尝试将某些IP地址列入白名单,以便只有使用特定网络集的用户才能访问我的Flask微服务的REST端点。

代码示例:

我有一个这样的装饰器:

def check_ip(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        headers_list = request.headers.getlist("HTTP_X_FORWARDED_FOR")
        ip = headers_list[0] if headers_list else request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
        current_app.logger.info(
            {'client_ip_address': request.json['ip']
             }
        )
        if ip:
            if ip in allowed_ip_addresses:
                return f(*args, **kwargs)

        return {'message': 'Forbidden to Access'}, 403

    return decorated

错误:

我面临的问题是,检测到的IP地址始终为127.0.0.1(localhost)。我似乎无法获得请求的正确IP地址。任何帮助将不胜感激!

所需的解决方案:

我希望能够获取发送到API的请求的正确IP地址

要求:

我正在使用Flask,并将其部署到生产环境中时,它将在Gunicorn上运行

0 个答案:

没有答案
相关问题