使用 Flask for Python 获取访问者的 IP 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3759981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get IP address of visitors using Flask for Python
提问by Jon Cox
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).
我正在制作一个网站,用户可以使用Flask 微框架(基于Werkzeug)登录并下载文件,该框架使用 Python(在我的情况下为 2.6)。
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?
我需要在用户登录时获取用户的 IP 地址(用于日志记录)。有谁知道如何做到这一点?肯定有办法用 Python 做到这一点吗?
采纳答案by Tarantula
See the documentation on how to access the Request objectand then get from this same Request object, the attribute remote_addr.
请参阅有关如何访问 Request 对象然后从同一个 Request 对象获取属性的文档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.
有关更多信息,请参阅Werkzeug 文档。
回答by davidg
The user's IP address can be retrieved using the following snippet:
可以使用以下代码段检索用户的 IP 地址:
from flask import request
print(request.remote_addr)
回答by Chiedo
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:
如果您想要客户端 IP 地址,请使用以下命令:
request.environ['REMOTE_ADDR']
回答by Stephen Fuhry
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.environin your particular environment. With nginx I will sometimes do something like this:
代理可能会使这有点棘手,如果您正在使用代理,请务必查看ProxyFix(Flask 文档)。看看request.environ您的特定环境。使用 nginx 我有时会做这样的事情:
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.
当代理(例如 nginx)转发地址时,它们通常会在请求标头中的某处包含原始 IP。
UpdateSee the flask-security implementation. Again, review the documentation about ProxyFix before implementing. Your solution may vary based on your particular environment.
更新请参阅flask-security implementation。同样,在实施之前查看有关 ProxyFix 的文档。您的解决方案可能因您的特定环境而异。
回答by Pegasus
httpbin.orguses this method:
httpbin.org使用这种方法:
return jsonify(origin=request.headers.get('X-Forwarded-For', request.remote_addr))
回答by raviv
This should do the job. It provides the client IP address (remote host).
这应该可以完成工作。它提供客户端 IP 地址(远程主机)。
Note that this code is running on the server side.
请注意,此代码在服务器端运行。
from mod_python import apache
req.get_remote_host(apache.REMOTE_NOLOOKUP)
回答by Tirtha R
The below code always gives the public IP of the client (and not a private IP behind a proxy).
下面的代码总是提供客户端的公共 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
回答by Soli
I have Nginxand With below Nginx Config:
我有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-rsolution 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......"
}
回答by Vlad
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:
如果您在其他平衡器(例如 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
回答by Jyotiprakash panigrahi
If You are using Gunicorn and Nginx environment then the following code template works for you.
如果您使用 Gunicorn 和 Nginx 环境,那么以下代码模板适合您。
addr_ip4 = request.remote_addr

