怎么在Python中使用django框架现获取访问者ip地址-创新互联
本篇文章为大家展示了怎么在Python中使用django框架现获取访问者ip地址,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
枣阳ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联建站的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18980820575(备注:SSL证书合作)期待与您的合作!python是什么意思
Python是一种跨平台的、具有解释性、编译性、互动性和面向对象的脚本语言,其最初的设计是用于编写自动化脚本,随着版本的不断更新和新功能的添加,常用于用于开发独立的项目和大型项目。
在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:
•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+.
然后我们来打印一下其中的条目进行验证:
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.'})
上述内容就是怎么在Python中使用django框架现获取访问者ip地址,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联成都网站设计公司行业资讯频道。
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网站栏目:怎么在Python中使用django框架现获取访问者ip地址-创新互联
分享链接:http://hbruida.cn/article/dopish.html