在瓶装饰功能获取IP地址和端口[复制]

问题描述 投票:-1回答:1

这个问题已经在这里有一个答案:

如何获得在一个装饰功能瓶发送该请求的客户端的IP地址和端口?

from flask import Flask, request, jsonify
from functools import wraps
app = Flask(__name__)

def check_auth(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        print(request)
        ###  Here I need the IP address and port of the client
        return f(*args, **kwargs)
    return decorated_function

@app.route('/test', methods=['POST'])
@check_auth
def hello():
    json = request.json
    json['nm'] = 'new name2'
    jsonStr = jsonify(json)
    return jsonStr
python python-3.x flask flask-restful
1个回答
1
投票

您可以使用瓶的request.environ()函数来获取客户端的远程端口和IP地址:

from flask import request
from functools import wraps

def check_auth(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        print(request)
        ###  Here I need the IP address and port of the client
        print("The client IP is: {}".format(request.environ['REMOTE_ADDR']))
        print("The client port is: {}".format(request.environ['REMOTE_PORT']))
        return f(*args, **kwargs)
    return decorated_function

该装饰印刷是这样的:

The client IP is: 127.0.0.1
The client port is: 12345
© www.soinside.com 2019 - 2024. All rights reserved.