Django 获取用户IP

获取代理函数

python 复制代码
def get_ip(request):
    # 判断是否使用代理
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        # 使用代理获取真实的ip
        ip = x_forwarded_for.split(',')[0]
    else:
        # 未使用代理获取IP
        ip = request.META.get('REMOTE_ADDR')

    return HttpResponse('{"origin": "%s"}' % ip)

生产环境配置NGINX

bash 复制代码
# nginx配置
location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

在使用NGINX做负载均衡的生产环境中如果不配置NGINX,那么 request.META.get('REMOTE_ADDR') 获取到的是NGINX负载均衡proxy_pass 127.0.0.1 IP,而不是实际用户IP

相关推荐
Lupino2 小时前
别再只聊 AI 写代码了:技术负责人要把“变更治理”提到第一优先级
python·docker·容器
Flittly4 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(6)Context Compact (上下文压缩)
python·agent
曲幽15 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户83562907805120 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞1 天前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派1 天前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪1 天前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户0332126663671 天前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫1 天前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派1 天前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain