本文实例讲述了Python django框架应用中实现获取访问者ip地址。分享给大家供大家参考,具体如下:
在django官方文档中有一段对request.META的解释:
HttpRequest.META
A standard Python dictionary containing all available HTTP headers. Available headers depend on the client
and server, but here are some examples:
"GET" or "POST".
"htmlcode">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:
#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信息:
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.'})PS:这里再为大家推荐一款功能相似的在线工具供大家参考:
IP地址归属地在线查询工具:
http://tools.jb51.net/aideddesign/ipcha另外,本站在线工具小程序上也有一款功能更加强大的IP地址解析工具,感兴趣的朋友可以扫描如下小程序码查看:
希望本文所述对大家基于Django框架的Python程序设计有所帮助。