Retrieving Visitors' IP Addresses in Flask for Python
Question:
In a Flask-based Python website that allows users to log in and download files, how can one obtain the IP addresses of visitors upon login for logging purposes?
Answer:
To retrieve the IP addresses of visitors in a Flask application using Python, you can leverage the Werkzeug framework upon which Flask is built. Here's how you can do it:
Code Example:
<code class="python">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</code>
Explanation:
In this code, we obtain the Request object using the request import from Flask. This object provides access to various request-related information, including the remote_addr attribute, which contains the IP address of the user making the request. We then jsonify the IP address and return it as a response.
Further Information:
For additional insights, refer to the Werkzeug documentation for more details on accessing request attributes and additional request handling methods.
The above is the detailed content of How to Get Visitors\' IP Addresses in a Flask-Based Python Website?. For more information, please follow other related articles on the PHP Chinese website!