环境:
- centos 7.5
- python 3.6
- django 2.2.7
- requests 2.22.0
- retrying 1.3.3
相关配置可去这篇文章查看:
Python Django 搭建纯净IP地址返回服务(返回访问者IP地址)
记录用户访问页面
==获取用户访问页面==
==server_name = request.META.get('SERVER_NAME')==
def get_ip(request):
"""获取访问页面及客户端ip地址"""
ip = None
proxy_ip = None
server_name = request.META.get('SERVER_NAME')
if request.META.get('HTTP_X_FORWARDED_FOR'):
ip = request.META.get("HTTP_X_FORWARDED_FOR")
proxy_ip = request.META.get("REMOTE_ADDR")
else:
ip = request.META.get("REMOTE_ADDR")
# 获取物理地址
try:
address = ip_address(ip)
except:
address = '获取失败'
# 写入日志文件
log_init().info(f'{server_name} {ip} {address}')
return HttpResponse(ip)
IP地址定位查询
@retry(stop_max_attempt_number=5)
def ip_address(ip):
"""ip地址查询物理地址"""
url = f'http://api.map.*****.com/location/ip?ak=*******j&ip={ip}&coor=bd09ll'
rsp = requests.get(url, timeout=10).text
content = json.loads(rsp)
# 请求状态 0有数据 1无数据
status = content['status']
if status:
return content['message']
address = content['content']['address']
return address
保存访问日志
微信截图_20200331024739.pngPS:目前只能正确查询国内IP,外网IP查询会失败,暂时满足目前需求,后续更新查询外网IP地址方法。
本文仅供学习交流使用,如侵立删!
企鹅 、WX: 1033383881
网友评论