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

发布于 2024-09-24 11:08:53 字数 251 浏览 9 评论 0原文

我正在制作一个网站,用户可以使用 Flask 微框架(基于Werkzeug)它使用Python(在我的例子中是2.6)。

我需要在用户登录时获取他们的 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

红尘作伴 2024-10-01 11:08:53

请参阅有关如何访问 Request 对象的文档,然后从同样的 Request 对象,属性 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.

夜血缘 2024-10-01 11:08:53

代理可能会让这件事变得有点棘手,请务必查看 ProxyFixFlask 文档)如果您正在使用一个。查看您特定环境中的 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.

围归者 2024-10-01 11:08:53

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

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']
漫雪独思 2024-10-01 11:08:53

下面的代码始终给出客户端的公共 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
暮凉 2024-10-01 11:08:53

我有 Nginx 和以下 Nginx 配置

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< /a> 解决方案对我有用

#!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......"
}
贩梦商人 2024-10-01 11:08:53

可以使用以下代码片段检索用户的 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)
烈酒灼喉 2024-10-01 11:08:53

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))
﹏半生如梦愿梦如真 2024-10-01 11:08:53

如果您在其他平衡器(例如 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
伴随着你 2024-10-01 11:08:53

这是最简单的解决方案,以及如何在生产中使用。

from flask import Flask, request
from werkzeug.middleware.proxy_fix import ProxyFix
app = Flask(__name__)
# Set environment from any X-Forwarded-For headers if proxy is configured properly
app.wsgi_app = ProxyFix(app.wsgi_app, x_host=1)

@app.before_request
def before_process():
   ip_address = request.remote_addr

include proxy_params 添加到 /etc/nginx/sites-available/$project

  location / {
    proxy_pass http://unix:$project_dir/gunicorn.sock;
    include proxy_params;
  }

include proxy_params 转发由 ProxyFix 解析的以下标头。

$ sudo cat /etc/nginx/proxy_params 
proxy_set_header Host $http_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;

Here is the simplest solution, and how to use in production.

from flask import Flask, request
from werkzeug.middleware.proxy_fix import ProxyFix
app = Flask(__name__)
# Set environment from any X-Forwarded-For headers if proxy is configured properly
app.wsgi_app = ProxyFix(app.wsgi_app, x_host=1)

@app.before_request
def before_process():
   ip_address = request.remote_addr

Add include proxy_params to /etc/nginx/sites-available/$project.

  location / {
    proxy_pass http://unix:$project_dir/gunicorn.sock;
    include proxy_params;
  }

include proxy_params forwards the following headers which are parsed by ProxyFix.

$ sudo cat /etc/nginx/proxy_params 
proxy_set_header Host $http_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;
幸福丶如此 2024-10-01 11:08:53

如果您使用 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
╰沐子 2024-10-01 11:08:53

这应该可以完成工作。
它提供客户端 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)
倾城花音 2024-10-01 11:08:53

我没有通过 Google Cloud App Engine 获得上述任何工作。这有效,但是

ip = request.headers['X-Appengine-User-Ip']

建议的 request.remote_addr 每次都只返回本地主机 IP。

I did not get any of the above work with Google Cloud App Engine. This worked, however

ip = request.headers['X-Appengine-User-Ip']

The proposed request.remote_addr did only return local host ip every time.

窗影残 2024-10-01 11:08:53

如果使用 Cloudflare Argo 隧道,请使用:

ip_address = request.environ['HTTP_CF_CONNECTING_IP']

If using Cloudflare Argo Tunnels, use:

ip_address = request.environ['HTTP_CF_CONNECTING_IP']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文