问题:使用Flask for Python获取访问者的IP地址

我正在建立一个网站,用户可以使用使用Python(在我的情况下为2.6)的Flask微框架(基于Werkzeug)登录和下载文件。

我需要获得用户登录时的IP地址(出于记录目的)。有谁知道如何做到这一点?当然有办法用Python做到吗?

I’m making a website where users can log on and download files, using the Flask micro-framework (based on Werkzeug) which uses Python (2.6 in my case).

I need to get the IP address of users when they log on (for logging purposes). Does anyone know how to do this? Surely there is a way to do it with Python?


回答 0

请参阅有关如何访问Request对象,然后从同一Request对象(即attribute)获取文档remote_addr

代码示例

from flask import request
from flask import jsonify

@app.route("/get_my_ip", methods=["GET"])
def get_my_ip():
    return jsonify({'ip': request.remote_addr}), 200

有关更多信息,请参阅Werkzeug文档

See the documentation on how to access the Request object and then get from this same Request object, the attribute remote_addr.

Code example

from flask import request
from flask import jsonify

@app.route("/get_my_ip", methods=["GET"])
def get_my_ip():
    return jsonify({'ip': request.remote_addr}), 200

For more information see the Werkzeug documentation.


回答 1

代理会使这变得有些棘手,如果使用代理,请确保签出ProxyFixFlask docs)。看一下request.environ您的特定环境。使用nginx,有时我会做这样的事情:

from flask import request   
request.environ.get('HTTP_X_REAL_IP', request.remote_addr)   

当代理(例如nginx)转发地址时,它们通常在请求标头中的某处包括原始IP。

更新 请参见flask-security实现。同样,在实施之前,请阅读有关ProxyFix的文档。您的解决方案可能会因您的特定环境而异。

Proxies can make this a little tricky, make sure to check out ProxyFix (Flask docs) if you are using one. Take a look at request.environ in your particular environment. With nginx I will sometimes do something like this:

from flask import request   
request.environ.get('HTTP_X_REAL_IP', request.remote_addr)   

When proxies, such as nginx, forward addresses, they typically include the original IP somewhere in the request headers.

Update See the flask-security implementation. Again, review the documentation about ProxyFix before implementing. Your solution may vary based on your particular environment.


回答 2

实际上,您将发现,仅获取以下内容即可获得服务器的地址:

request.remote_addr

如果要客户端IP地址,请使用以下命令:

request.environ['REMOTE_ADDR']

Actually, what you will find is that when simply getting the following will get you the server’s address:

request.remote_addr

If you want the clients IP address, then use the following:

request.environ['REMOTE_ADDR']

回答 3

可以使用以下代码段检索用户的IP地址:

from flask import request
print(request.remote_addr)

The user’s IP address can be retrieved using the following snippet:

from flask import request
print(request.remote_addr)

回答 4

我有Nginx并且在Nginx Config下面:

server {
    listen 80;
    server_name xxxxxx;
    location / {
               proxy_set_header   Host                 $host;
               proxy_set_header   X-Real-IP            $remote_addr;
               proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;
               proxy_set_header   X-Forwarded-Proto    $scheme;

               proxy_pass http://x.x.x.x:8000;
        }
}

@ tirtha-r解决方案为我工作

#!flask/bin/python
from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/', methods=['GET'])
def get_tasks():
    if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
        return jsonify({'ip': request.environ['REMOTE_ADDR']}), 200
    else:
        return jsonify({'ip': request.environ['HTTP_X_FORWARDED_FOR']}), 200

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0', port=8000)

我的要求和回应:

curl -X GET http://test.api

{
    "ip": "Client Ip......"
}

I have Nginx and With below Nginx Config:

server {
    listen 80;
    server_name xxxxxx;
    location / {
               proxy_set_header   Host                 $host;
               proxy_set_header   X-Real-IP            $remote_addr;
               proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;
               proxy_set_header   X-Forwarded-Proto    $scheme;

               proxy_pass http://x.x.x.x:8000;
        }
}

@tirtha-r solution worked for me

#!flask/bin/python
from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/', methods=['GET'])
def get_tasks():
    if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
        return jsonify({'ip': request.environ['REMOTE_ADDR']}), 200
    else:
        return jsonify({'ip': request.environ['HTTP_X_FORWARDED_FOR']}), 200

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0', port=8000)

My Request and Response:

curl -X GET http://test.api

{
    "ip": "Client Ip......"
}

回答 5

以下代码始终提供客户端的公共IP(而不是代理后面的私有IP)。

from flask import request

if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
    print(request.environ['REMOTE_ADDR'])
else:
    print(request.environ['HTTP_X_FORWARDED_FOR']) # if behind a proxy

The below code always gives the public IP of the client (and not a private IP behind a proxy).

from flask import request

if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
    print(request.environ['REMOTE_ADDR'])
else:
    print(request.environ['HTTP_X_FORWARDED_FOR']) # if behind a proxy

回答 6

httpbin.org使用以下方法:

return jsonify(origin=request.headers.get('X-Forwarded-For', request.remote_addr))

httpbin.org uses this method:

return jsonify(origin=request.headers.get('X-Forwarded-For', request.remote_addr))

回答 7

如果您在其他平衡器(例如AWS Application Balancer)之后使用Nginx,则HTTP_X_FORWARDED_FOR返回地址列表。可以这样修复:

if 'X-Forwarded-For' in request.headers:
    proxy_data = request.headers['X-Forwarded-For']
    ip_list = proxy_data.split(',')
    user_ip = ip_list[0]  # first address in list is User IP
else:
    user_ip = request.remote_addr  # For local development

If you use Nginx behind other balancer, for instance AWS Application Balancer, HTTP_X_FORWARDED_FOR returns list of addresses. It can be fixed like that:

if 'X-Forwarded-For' in request.headers:
    proxy_data = request.headers['X-Forwarded-For']
    ip_list = proxy_data.split(',')
    user_ip = ip_list[0]  # first address in list is User IP
else:
    user_ip = request.remote_addr  # For local development

回答 8

如果您使用的是Gunicorn和Nginx环境,则以下代码模板适用于您。

addr_ip4 = request.remote_addr

If You are using Gunicorn and Nginx environment then the following code template works for you.

addr_ip4 = request.remote_addr

回答 9

这应该做的工作。它提供客户端IP地址(远程主机)。

请注意,此代码在服务器端运行。

from mod_python import apache

req.get_remote_host(apache.REMOTE_NOLOOKUP)

This should do the job. It provides the client IP address (remote host).

Note that this code is running on the server side.

from mod_python import apache

req.get_remote_host(apache.REMOTE_NOLOOKUP)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。