Accessing Visitor IP Addresses with Python and Flask
When developing web applications, logging user details such as IP addresses can be essential for security and analytical purposes. This question revolves around the need to retrieve visitor IP addresses while using the Flask micro-framework based on Werkzeug.
To obtain the IP address of visitors using Flask in Python, follow these steps:
Import the Flask Request Object:
<code class="python">from flask import request</code>
Example Code:
Here's an example of a Flask route that returns the IP address of the visitor as a JSON response:
<code class="python">@app.route("/get_my_ip", methods=["GET"]) def get_my_ip(): return jsonify({"ip": request.remote_addr}), 200</code>
For more details, refer to the Werkzeug documentation, which offers a comprehensive guide to working with request objects in Flask, including IP address retrieval: [Werkzeug Documentation](https://werkzeug.palletsprojects.com/en/1.0.x/request/).
The above is the detailed content of How do I retrieve visitor IP addresses using Flask in Python?. For more information, please follow other related articles on the PHP Chinese website!