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根据经纬度计算距离示例
Feb 16 Python
python实现连接mongodb的方法
May 08 Python
Python深入06——python的内存管理详解
Dec 07 Python
Python爬豆瓣电影实例
Feb 23 Python
Python实现的根据IP地址计算子网掩码位数功能示例
May 23 Python
Python实现使用request模块下载图片demo示例
May 24 Python
pandas 数据索引与选取的实现方法
Jun 21 Python
Python 获取指定文件夹下的目录和文件的实现
Aug 30 Python
Centos7下源码安装Python3 及shell 脚本自动安装Python3的教程
Mar 07 Python
Python matplotlib绘制图形实例(包括点,曲线,注释和箭头)
Apr 17 Python
用python写爬虫简单吗
Jul 28 Python
python 解决selenium 中的 .clear()方法失效问题
Sep 01 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
我常用的几个类
2006/10/09 PHP
用PHP和ACCESS写聊天室(五)
2006/10/09 PHP
table标签的结构与合并单元格的实现方法
2013/07/24 PHP
php使用SAE原生Mail类实现各种类型邮件发送的方法
2016/10/10 PHP
基于laravel-admin 后台 列表标签背景的使用方法
2019/10/03 PHP
PHP中类与对象功能、用法实例解读
2020/03/27 PHP
js读写cookie实现一个底部广告浮层效果的两种方法
2013/12/29 Javascript
纯JS实现本地图片预览的方法
2015/07/31 Javascript
Angular.js与Bootstrap相结合实现表格分页代码
2016/04/12 Javascript
无缝滚动的简单实现代码(推荐)
2016/06/07 Javascript
基于Bootstrap的后台管理面板 Bootstrap Metro Dashboard
2016/06/17 Javascript
用自定义图片代替原生checkbox实现全选,删除以及提交的方法
2016/10/18 Javascript
JS获取浮动(float)元素的style.left值为空的快速解决办法
2017/02/19 Javascript
vue-resourse将json数据输出实例
2017/03/08 Javascript
ES6新特性之数组、Math和扩展操作符用法示例
2017/04/01 Javascript
Node.js使用Angular简单示例
2018/05/11 Javascript
vue使用better-scroll实现下拉刷新、上拉加载
2018/11/23 Javascript
详解angularjs4部署文件过大解决过程
2018/12/05 Javascript
vue实现循环滚动列表
2020/06/30 Javascript
[03:27]《辉夜杯》线下训练营 导师CU和海涛指点迷津
2015/10/23 DOTA
Python入门篇之条件、循环
2014/10/17 Python
Python解决鸡兔同笼问题的方法
2014/12/20 Python
Python字符串格式化
2015/06/15 Python
深入浅出分析Python装饰器用法
2017/07/28 Python
python encrypt 实现AES加密的实例详解
2020/02/20 Python
Python写捕鱼达人的游戏实现
2020/03/31 Python
HTML5 绘制图像(上)之:关于canvas元素引领下一代web页面的问题
2013/04/24 HTML / CSS
发现世界上最好的珠宝设计师:JewelStreet
2017/12/17 全球购物
企业治理工作自我评价
2013/09/26 职场文书
教师开学感言
2014/02/14 职场文书
社区巾帼文明岗事迹材料
2014/06/03 职场文书
文艺演出策划方案
2014/06/07 职场文书
因工资原因离职的辞职信范文
2015/05/12 职场文书
授权协议书范本(3篇)
2019/10/15 职场文书
导游词之介休绵山
2019/12/31 职场文书
Django框架中视图的用法
2022/06/10 Python