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实现socket端口重定向示例
Feb 10 Python
python验证码识别实例代码
Feb 03 Python
python实现数独游戏 java简单实现数独游戏
Mar 30 Python
python 保存float类型的小数的位数方法
Oct 17 Python
Python3最长回文子串算法示例
Mar 04 Python
Python基于scipy实现信号滤波功能
May 08 Python
如何使用python爬虫爬取要登陆的网站
Jul 12 Python
python自动化unittest yaml使用过程解析
Feb 03 Python
python GUI库图形界面开发之PyQt5菜单栏控件QMenuBar的详细使用方法与实例
Feb 28 Python
pyspark 随机森林的实现
Apr 24 Python
PyCharm上安装Package的实现(以pandas为例)
Sep 18 Python
python 利用opencv实现图像网络传输
Nov 12 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
电脑硬件及电脑配置知识大全
2020/03/17 数码科技
php中XMLHttpRequest(Ajax)不能设置自定义的Referer的解决方法
2011/11/26 PHP
php 启动报错如何解决
2014/01/17 PHP
[原创]php简单防盗链验证实现方法
2016/07/09 PHP
PHP实现腾讯与百度坐标转换
2017/08/05 PHP
laravel 解决groupBy时出现的错误 isn't in Group By问题
2019/10/17 PHP
js 遍历对象的属性的代码
2011/12/29 Javascript
jqGrid日期格式的判断示例代码(开始日期与结束日期)
2013/11/08 Javascript
JavaScript操作XML/HTML比较常用的对象属性集锦
2015/10/30 Javascript
JS实现太极旋转思路分析
2016/12/09 Javascript
Bootstrap基本模板的使用和理解1
2016/12/14 Javascript
详解react-router4 异步加载路由两种方法
2017/09/12 Javascript
安装vue-cli的简易过程
2018/05/22 Javascript
通过封装scroll.js 获取滚动条的值
2018/07/13 Javascript
select2 ajax 设置默认值,初始值的方法
2018/08/09 Javascript
微信小程序如何连接Java后台
2019/08/08 Javascript
Node.js之删除文件夹(含递归删除)代码实例
2019/09/09 Javascript
微信小程序实现3D轮播图效果(非swiper组件)
2019/09/21 Javascript
Vue组件模板及组件互相引用代码实例
2020/03/11 Javascript
[00:10]DOTA2全国高校联赛 以DOTA2会友
2018/05/30 DOTA
python简单实现计算过期时间的方法
2015/06/09 Python
python计算文本文件行数的方法
2015/07/06 Python
Python使用requests发送POST请求实例代码
2018/01/25 Python
用python实现k近邻算法的示例代码
2018/09/06 Python
Python并行分布式框架Celery详解
2018/10/15 Python
python write无法写入文件的解决方法
2019/01/23 Python
python读取图片的方式,以及将图片以三维数组的形式输出方法
2019/07/03 Python
Pytorch中.new()的作用详解
2020/02/18 Python
Django中日期时间型字段进行年月日时分秒分组统计
2020/11/27 Python
师德学习感言
2014/01/31 职场文书
简历的自我评价范文
2014/02/04 职场文书
《赠汪伦》教学反思
2014/04/12 职场文书
《菜园里》教学反思
2014/04/17 职场文书
安全负责人任命书
2014/06/06 职场文书
爱心助学感谢信
2015/01/21 职场文书
大学生毕业个人总结
2015/02/15 职场文书