在Flask装饰器函数中获取IP地址和端口

时间:2019-02-07 05:38:07

标签: python python-3.x flask flask-restful

如何在Flask中获得装饰器函数的发送请求的客户端的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

1 个答案:

答案 0 :(得分:1)

您可以使用Flask的QUERY ... LIKE :token $stmt->bindValue(":token", '%' . $searchString . '%', SQLITE3_TEXT); 函数来获取客户端的远程端口和IP地址:

request.environ()

装饰器打印如下内容:

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