Django框架中获取访问者真实IP地址的方法

半杯拿铁
半杯拿铁
发布时间:2026-10-14| 5人浏览过
原创

本文详解在Django框架中如何准确获取访问者IP。通过解析HttpRequest.META字典,利用REMOTE_ADDR和HTTP_X_FORWARDED_FOR键值,结合代理服务器场景,提供获取真实客户端IP的完整代码示例及登录日志记录方案。

Django获取访问者IP的方法

本文介绍在Python Django框架应用中获取访问者IP地址的具体实现方法,供读者参考学习。

根据Django官方文档说明,HttpRequest.META是一个标准的Python字典,包含所有可用的HTTP请求头信息。

HttpRequest.META A standard Python dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples: •CONTENT_LENGTH – The length of the request body (as a string). •CONTENT_TYPE – The MIME type of the request body. •HTTP_ACCEPT – Acceptable content types for the response. •HTTP_ACCEPT_ENCODING – Acceptable encodings for the response. •HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response. •HTTP_HOST – The HTTP Host header sent by the client. •HTTP_REFERER – The referring page, if any. •HTTP_USER_AGENT – The client's user-agent string. •QUERY_STRING – The query string, as a single (unparsed) string. •REMOTE_ADDR – The IP address of the client. •REMOTE_HOST – The hostname of the client. •REMOTE_USER – The user authenticated by the Web server, if any. •REQUEST_METHOD – A string such as "GET" or "POST". •SERVER_NAME – The hostname of the server. •SERVER_PORT – The port of the server (as a string). With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER. Note that runserver strips all headers with underscores in the name, so you won't see them in META. This prevents header-spoofing based on ambiguity between underscores and dashes both being normalizing to under- scores in WSGI environment variables. It matches the behavior of Web servers like Nginx and Apache 2.4+.

为了验证META字典中的内容,我们可以打印其中的键值对进行查看。


request_meta = request.META
info = []
for k, v in request_meta.items():
info.append(k)
print info
>>>
['wsgi.version', 'RUN_MAIN', 'HTTP_REFERER', 'HTTP_HOST', 'SERVER_PROTOCOL', 'SERVER_SOFTWARE', 'SCRIPT_NAME', 'LESSOPEN', 'SSH_CLIENT', 'REQUEST_METHOD', 'LOGNAME', 'USER', 'HOME', 'QUERY_STRING', 'PATH', 'MYSQL_DATABASE_URI', 'wsgi.errors', 'TERADATA_JACKAL_URI', 'LANG', 'TERM', 'SHELL', 'TZ', 'HTTP_COOKIE', 'J2REDIR', 'REMOTE_ADDR', 'SHLVL', 'wsgi.url_scheme', 'HTTP_VIA', 'SERVER_PORT', 'wsgi.file_wrapper', 'JAVA_HOME', 'CONTENT_LENGTH', 'HTTP_CONNECTION', 'XDG_RUNTIME_DIR', 'TERADATA_PASSWORD', 'PYTHONPATH', 'COMP_WORDBREAKS', 'VIRTUAL_ENV', u'CSRF_COOKIE', 'J2SDKDIR', 'wsgi.input', 'HTTP_USER_AGENT', 'PS1', 'wsgi.multithread', 'HTTP_UPGRADE_INSECURE_REQUESTS', 'HTTP_CACHE_CONTROL', 'XDG_SESSION_ID', '_', 'HTTP_ACCEPT', 'DERBY_HOME', 'SSH_CONNECTION', 'LESSCLOSE', 'SERVER_NAME', 'GATEWAY_INTERFACE', 'HTTP_X_FORWARDED_FOR', 'SSH_TTY', 'OLDPWD', 'wsgi.multiprocess', 'HTTP_ACCEPT_LANGUAGE', 'wsgi.run_once', 'PWD', 'DJANGO_SETTINGS_MODULE', 'CONTENT_TYPE', 'TERADATA_SIMBA_URI', 'MAIL', 'LS_COLORS', 'REMOTE_HOST', 'HTTP_ACCEPT_ENCODING', 'PATH_INFO']

通常访问者的IP地址信息会包含在上述键值对中,我们可以通过特定方式提取该IP。

既然访问者的IP通常存在于其中,我们可以采用以下方法来获取用户的真实IP地址。

获取真实IP的代码实现


#X-Forwarded-For:简称XFF头,它代表客户端,也就是HTTP的请求端真实的IP,只有在通过了HTTP 代理或者负载均衡服务器时才会添加该项。
def get_ip(request):
 x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
 if x_forwarded_for:
  ip = x_forwarded_for.split(',')[0]#所以这里是真实的ip
 else:
  ip = request.META.get('REMOTE_ADDR')#这里获得代理ip
 return ip

结合之前的日志模块功能,我们可以实现记录登录用户IP信息的功能。

结合日志模块记录登录IP


remote_info = ''
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
 remote_info = 'HTTP_X_FORWARDED_FOR:' + x_forwarded_for.split(',')[0]
remote_addr = request.META.get('REMOTE_ADDR')
if remote_addr:
 remote_info += ' REMOTE_ADDR:' + remote_addr
if pass_auth:
 user.last_login_at = timezone.now()
 try:
  user.save()
 except Exception, msg:
  return JsonResponse({'result': 'Error', 'message': str(msg)})
 request.session['user_id'] = user_id
 request.session.set_expiry(9000)
 logger.info('[Success] '+ user_id+' has logged in! '+remote_info)
 return JsonResponse({'result': 'Success', 'message': 'Login successfully.'})
else:
 logger.warning('[Failed] '+ user_id + ' failed to login! '+remote_info)
 return JsonResponse({'result': 'Error', 'message': 'Username or Password is incorrect.'})

此外,这里推荐一款功能相似的在线工具供参考。

IP地址归属地在线查询工具: http://tools.jb51.net/aideddesign/ipcha

另外,本站在线工具小程序上也有一款功能更加强大的IP地址解析工具,感兴趣的朋友可以扫描如下小程序码查看:

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。