SoFunction
Updated on 2024-11-19

Python's Flask project to get the IP address of the requesting user addr problem

Python Flask project to get the IP address of the requesting user addr

Direct server deployment of Flask

import logging
from flask import Flask, render_template, request

# Initialize the Flask application
app = Flask(__name__)

# Default route, print user's IP
@('/')
def index():
     ip = request.remote_addr
     (ip)
     return render_template('', user_ip=ip)


if __name__ == '__main__':
     (host="0.0.0.0", port=80)

Starting Flask in Nginx Proxy Gunicorn in Docker

In this case, the code above will only get the local server address. You need to use .proxy_fix.

import logging
from flask import Flask, render_template, request
from .proxy_fix import ProxyFix

# Initialize the Flask application
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=1)


# Default route, print user's IP
@('/')
def index():
     ip = request.remote_addr
     (ip)
     return render_template('', user_ip=ip)

We can do something about the IP.

Flask to get the user's ip, query the user's login times, and block ip

Python flask (request request)

Note that the parameter is used to get the

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from flask import Flask, jsonify, abort, request

app = Flask(__name__)

result = [
    { 
        "code":"001",
        "desc":"success",
        "data":1
    }
]

@('/')
def hello_world():
    return 'Hello World!'

@('/send/imgaddress', methods=['POST'])
def create_task():
    getdata = ('utf-8')
    userImg = ''
    userdebugImg = ''
    userImg = ('user')
    userdebugImg = ('userdebug')
    print('userImg:', userImg)
    print('userdebugImg:', userdebugImg)
    result[0]["code"] = '001'
    return jsonify({'result': result})

if __name__ == "__main__":
    (debug=True)

test (machinery etc)

http://127.0.0.1:5000/send/imgaddress?user=172.28.6.1&userdebug=172.28.6.0

Cross-computer access on the same LAN

You can note that the ip used above is 127.0.0.1, then use the local computer ip how to set it?

Modify the following:

if __name__ == "__main__":
    (host="0.0.0.0", debug=False)

Allow cross-group access

app = Flask(__name__)

Change to:

from flask_cors import CORS
app = Flask(__name__)
CORS(app, supports_credentials=True)

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.