在Flask装饰器功能中获取IP地址和端口[重复]
Posted
技术标签:
【中文标题】在Flask装饰器功能中获取IP地址和端口[重复]【英文标题】:Get IP address and port in Flask decorator function [duplicate] 【发布时间】:2019-07-01 04:37:43 【问题描述】:如何在 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】:您可以使用 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
【讨论】:
以上是关于在Flask装饰器功能中获取IP地址和端口[重复]的主要内容,如果未能解决你的问题,请参考以下文章