Get IP address of visitors using Flask for Python
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.
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.
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']