pythonflaskip-addresswerkzeug

Get IP address of visitors using Flask for Python


I'm making a website where users can log on and download files, using the Flask micro-framework (based on Werkzeug) which uses Python (2.6 in my case).

I need to get the IP address of users when they log on (for logging purposes). Does anyone know how to do this? Surely there is a way to do it with Python?


Solution

  • 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.