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.
Python, Flask client ip address
How do you deploy the flask application?
I guess you deploy your app via a reverse-proxy server like nginx, right?
If you did that then request.remote_addr
is the address of your server because your server sent client's request to your application and sent the response to the client.
To fix this, see: http://flask.pocoo.org/docs/0.11/deploying/wsgi-standalone/#proxy-setups
Get IP address and port in Flask decorator function
You can use Flask's request.environ()
function to get the Remote port and IP Address for the client:
from flask import request
from functools import wraps
def check_auth(f):
@wraps(f)
def decorated_function(*args, **kwargs):
print(request)
### Here I need the IP address and port of the client
print("The client IP is: {}".format(request.environ['REMOTE_ADDR']))
print("The client port is: {}".format(request.environ['REMOTE_PORT']))
return f(*args, **kwargs)
return decorated_function
The decorator prints something like:
The client IP is: 127.0.0.1
The client port is: 12345
Related Topics
Saving a Numpy Array as an Image
How to Add a Constant Column in a Spark Dataframe
How to Get a Directory Listing Sorted by Creation Date in Python
Hexadecimal String to Byte Array in Python
Deprecationwarning: Executable_Path Has Been Deprecated Selenium Python
Why Does Random.Shuffle Return None
Python Subprocess Get Children's Output to File and Terminal
Getting the Class Name of an Instance
What Is a Cross-Platform Way to Get the Home Directory
Apply VS Transform on a Group Object
Django Media_Url and Media_Root
How to Convert String to Binary
What's the Scope of a Variable Initialized in an If Statement