You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Flask的新闻应用:获取用户真实IP与对应国家以提供定制新闻

Flask获取用户真实IP解决方法

你遇到的request.remote_addr返回127.0.0.1的问题,大多是因为应用部署在反向代理(比如Nginx、Apache)之后,此时remote_addr拿到的是代理服务器的IP,而非用户真实IP。以下是具体解决办法:

1. 从请求头获取真实IP

反向代理通常会将用户真实IP放在X-Forwarded-For请求头里,你可以优先读取这个值。注意该头可能包含多个IP(经过多层代理的情况),需要取第一个非本地的IP。

2. 修正你的代码

你的代码存在两个明显问题:

  • 函数名重复定义了get_user_country
  • 使用了requests但未导入模块

修正后的完整代码如下:

from flask import Flask, render_template, jsonify, request
import requests  # 补充导入requests模块
from x import IPINFO_API_KEY, DEFAULT_COUNTRY

def get_country_by_ip(ip_address):
    # 替换原重名函数
    response = requests.get(f'https://ipinfo.io/{ip_address}/country?token={IPINFO_API_KEY}')
    if response.status_code == 200:
        return response.text.strip()
    return None

@app.route('/api/user_country')
def get_user_country():
    # 优先从X-Forwarded-For获取真实IP, fallback到remote_addr
    ip_address = request.headers.get('X-Forwarded-For', request.remote_addr)
    
    # 处理多层代理下的多IP情况,取第一个有效IP
    if ',' in ip_address:
        ip_address = ip_address.split(',')[0].strip()
    
    print(f'ipaddress: {ip_address}')
    
    # 本地访问返回默认国家
    if ip_address in ('127.0.0.1', '::1', 'localhost'):
        return jsonify({'country': DEFAULT_COUNTRY})
    
    # 获取并返回国家信息
    country_code = get_country_by_ip(ip_address)
    if country_code:
        return jsonify({'country': country_code})
    else:
        return jsonify({'error': f'无法获取IP {ip_address}对应的国家信息'})

3. 配置反向代理(以Nginx为例)

如果用Nginx做代理,需要在配置中添加转发真实IP的请求头,确保Flask能拿到正确的用户IP:

location / {
    proxy_pass http://127.0.0.1:5000;  # 你的Flask应用地址
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;
}

4. 安全提示

不要盲目信任X-Forwarded-For头,建议在Flask中配置信任的代理IP,避免伪造IP的风险:

app = Flask(__name__)
# 配置信任的代理服务器IP(比如你的Nginx服务器公网IP)
app.config['TRUSTED_PROXIES'] = ['127.0.0.1', 'xxx.xxx.xxx.xxx']

内容的提问来源于stack exchange,提问作者Hex Heager

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 06:03:29