flask 获取客户端ip, 以及检查是不是内网ip
对于有nginx反向代理的请求,需要在nginx配置中添加如下内容:
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
然后在项目代码中获取ip
from flask import request
ip = request.access_route[0] if request.access_route else request.remote_addr
检查ip是不是内网
import ipaddress
def is_lan(ip):
try:
return ipaddress.ip_address(ip.strip()).is_private
except:
return False