Python django框架应用中实现获取访问者ip地址示例


Posted in Python onMay 17, 2019

本文实例讲述了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:
•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地址示例

Python 相关文章推荐
Python显示进度条的方法
Sep 20 Python
用Python的Django框架来制作一个RSS阅读器
Jul 22 Python
python中Switch/Case实现的示例代码
Nov 09 Python
python实现单链表中删除倒数第K个节点的方法
Sep 28 Python
Python实现带下标索引的遍历操作示例
May 30 Python
Python学习笔记之错误和异常及访问错误消息详解
Aug 08 Python
python在OpenCV里实现投影变换效果
Aug 30 Python
python tkinter canvas使用实例
Nov 04 Python
python双端队列原理、实现与使用方法分析
Nov 27 Python
python Plotly绘图工具的简单使用
Mar 03 Python
Python爬虫后获取重定向url的两种方法
Jan 19 Python
教你使用Python获取QQ音乐某个歌手的歌单
Apr 03 Python
Python Django框架实现应用添加logging日志操作示例
May 17 #Python
Python实现通过解析域名获取ip地址的方法分析
May 17 #Python
如何用C代码给Python写扩展库(Cython)
May 17 #Python
python实现坦克大战游戏 附详细注释
Mar 27 #Python
六行python代码的爱心曲线详解
May 17 #Python
python使用pygame模块实现坦克大战游戏
Mar 25 #Python
Django如何开发简单的查询接口详解
May 17 #Python
You might like
PHP has encountered an Access Violation
2007/01/15 PHP
PHP中的函数-- foreach()的用法详解
2013/06/24 PHP
ThinkPHP中的常用查询语言汇总
2014/08/22 PHP
php实现mysql备份恢复分卷处理的方法
2014/12/26 PHP
Javascript 日期处理之时区问题
2009/10/08 Javascript
onbeforeunload与onunload事件异同点总结
2013/06/24 Javascript
artdialog的图片/标题以及关闭按钮不显示的解决方法
2013/06/27 Javascript
js浮动图片的动态效果
2013/07/10 Javascript
基于jquery实现简单的手风琴特效
2015/11/24 Javascript
利用jquery实现下拉框的禁用与启用
2016/12/07 Javascript
详解vue事件对象、冒泡、阻止默认行为
2017/03/20 Javascript
百度地图去掉marker覆盖物或者去掉maker的label文字方法
2018/01/26 Javascript
深入理解令牌认证机制(token)
2019/08/22 Javascript
NodeJS配置CORS实现过程详解
2020/12/02 NodeJs
Python中的元类编程入门指引
2015/04/15 Python
如何在Python函数执行前后增加额外的行为
2016/10/20 Python
win10下Python3.6安装、配置以及pip安装包教程
2017/10/01 Python
python kmeans聚类简单介绍和实现代码
2018/02/23 Python
python中使用psutil查看内存占用的情况
2018/06/11 Python
关于Flask项目无法使用公网IP访问的解决方式
2019/11/19 Python
python实现矩阵和array数组之间的转换
2019/11/29 Python
Python同时处理多个异常的方法
2020/07/28 Python
移动端HTML5 input常见问题(小结)
2020/09/28 HTML / CSS
美国转售二手商品的电子商务平台:BLINQ
2018/12/13 全球购物
正宗的日本零食和糖果订阅盒:Bokksu
2019/11/21 全球购物
市场营销专业推荐信
2013/11/03 职场文书
2014年消防工作实施方案
2014/02/20 职场文书
初一学生评语大全
2014/04/24 职场文书
小学生勤俭节约演讲稿
2014/08/28 职场文书
2015年后备干部工作总结
2015/05/15 职场文书
2015暑期工社会实践报告
2015/07/13 职场文书
毕业欢送晚会主持词
2019/06/25 职场文书
Nginx服务器添加Systemd自定义服务过程解析
2021/03/31 Servers
使用python如何删除同一文件夹下相似的图片
2021/05/07 Python
Win11筛选键导致键盘失灵怎么解决? Win11关闭筛选键的技巧
2022/04/08 数码科技
Python进程间的通信之语法学习
2022/04/11 Python