下面是真实的ip地址获取方法
request_data = {}
if request.environ.get("HTTP_X_REAL_IP", False):
# 从环境信息获取
request_data['ip'] = request.environ.get("HTTP_X_REAL_IP", None)
elif request.headers.get("X-Real-Ip", False):
# 从头部信息获取
request_data['ip'] = request.headers.get("X-Real-Ip", None)
else:
# 获取一般的地址
request_data['ip'] = request.META['REMOTE_ADDR']
我是怎么获得的
for i in request.__dir__():
# 查看request所有的信息
try:
print(i, '()', eval(f"request.{i}()"), '\n',)
except:
print(i, eval(f"request.{i}"), '\n',)
print(request.environ.get("HTTP_X_REAL_IP", "environ['HTTP_X_REAL_IP']"), '\n\n\n')
print(request.environ.get("HTTP_ORIGIN", "environ['HTTP_ORIGIN']"), '\n\n\n')
以下失败的参考
#自定义中间件
from django.utils.deprecation import MiddlewareMixin
class SetRemoteAddrFromForwardedFor(MiddlewareMixin):
"""
如果部署了代理,使用此中间件获取远程客户端IP。
在settings中注册该中间件。
"""
def process_request(self, request):
try:
real_ip = request.META['HTTP_X_FORWARDED_FOR']
except KeyError as err:
print(err)
else:
real_ip = real_ip.split(",")[0]
request.META['REMOTE_ADDR'] = real_ip
# 中间件
MIDDLEWARE = [
...
'your_project.http.SetRemoteAddrFromForwardedFor',
]
#在程序中重新使用字典HttpRequest.META。
...
remote_ip = request.META.get('REMOTE_ADDR', '获取IP失败')
...
文章来源地址https://www.toymoban.com/news/detail-517009.html
文章来源:https://www.toymoban.com/news/detail-517009.html
到了这里,关于Django 获取真实ip地址的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!