个人用Django开发的博客已上线,欢迎访问:https://www.zhibibin.com
做网站时,需要获取用户的IP信息作为流量统计,目前比较流行的获取访问用户的IP方式是使用request.META属性,获取键值“HTTP_X_FORWARDED_FOR”或“REMOTE_ADDR来获取IP地址信息,其中关于“HTTP_X_FORWARDED_FOR”和“REMOTE_ADDR”的解释是:
- ’REMOTE_ADDR’ 是远端IP,默认来自tcp 连接是,客户端的Ip。可以说,它最准确,确定是,只会得到直接连服务器客户端IP。如果对方通过代理服务器上网,就发现。获取到的是代理服务器IP了。
- ’HTTP_X_FORWARDED_FOR’,’HTTP_CLIENT_IP’ 为了能在大型网络中,获取到最原始用户IP,或者代理IP地址。对HTTp协议进行扩展。定义了实体头。
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
然后把统计访问IP和访问数量更新到txt中:
def user_visit_statistics(request):
with open( TEMPLATE_DIR + r"/user_visit_number.txt", "r", encoding = "utf-8") as f:
number = f.readline()
user_visit_number = int(number)
user_ip = get_client_ip(request)
if user_ip != "":
user_visit_number += 1
with open( TEMPLATE_DIR + r"/user_visit_number.txt", "w", encoding = "utf-8") as f:
f.write(str(user_visit_number))
with open(TEMPLATE_DIR + r"/user_ip_address.txt", "a+", encoding="utf-8") as f:
f.write(time.strftime ('[%H:%M:%S] ', time.localtime ()))
f.write(user_ip)
f.write("\n")