Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Flask decorator函数中获取IP地址和端口_Python_Python 3.x_Flask_Flask Restful - Fatal编程技术网

Python 在Flask decorator函数中获取IP地址和端口

Python 在Flask decorator函数中获取IP地址和端口,python,python-3.x,flask,flask-restful,Python,Python 3.x,Flask,Flask Restful,如何在decorator函数中获取发送请求的客户端的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 ne

如何在decorator函数中获取发送请求的客户端的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
您可以使用Flask的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