Home  >  Article  >  Backend Development  >  How to Get Visitors\' IP Addresses in a Flask-Based Python Website?

How to Get Visitors\' IP Addresses in a Flask-Based Python Website?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 01:16:01416browse

How to Get Visitors' IP Addresses in a Flask-Based Python Website?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn