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网络编程学习笔记(七):HTML和XHTML解析(HTMLParser、BeautifulSoup)
Jun 09 Python
python获取指定网页上所有超链接的方法
Apr 04 Python
Python二分法搜索算法实例分析
May 11 Python
Python编程实现蚁群算法详解
Nov 13 Python
Django使用Celery异步任务队列的使用
Mar 13 Python
python对excel文档去重及求和的实例
Apr 18 Python
Python2.7.10以上pip更新及其他包的安装教程
Jun 12 Python
使用python将图片按标签分入不同文件夹的方法
Dec 08 Python
django 快速启动数据库客户端程序的方法示例
Aug 16 Python
python获取网络图片方法及整理过程详解
Dec 20 Python
python中使用input()函数获取用户输入值方式
May 03 Python
Pytest中skip和skipif的具体使用方法
Jun 30 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
destoon安全设置中需要设置可写权限的目录及文件
2014/06/21 PHP
php技术实现加载字体并保存成图片
2015/07/27 PHP
WordPress开发中自定义菜单的相关PHP函数使用简介
2016/01/05 PHP
PHP常用设计模式之委托设计模式
2016/02/13 PHP
PHP微信公众号开发之微信红包实现方法分析
2017/07/14 PHP
使用Git实现Laravel项目的自动化部署
2019/11/24 PHP
Laravel如何实现适合Api的异常处理响应格式
2020/06/14 PHP
User Scripts: Video Download by User Scripts
2007/05/14 Javascript
javascript 四则运算精度修正函数代码
2010/05/31 Javascript
jquery插件珍藏(图片局部放大/信息提示框)
2013/01/08 Javascript
javascript设计模式之工厂模式示例讲解
2014/03/04 Javascript
5个JavaScript经典面试题
2014/10/13 Javascript
js实现浮动在网页右侧的简洁QQ在线客服代码
2015/09/04 Javascript
一道JS前端闭包面试题解析
2015/12/25 Javascript
jQuery实现div拖拽效果实例分析
2016/02/20 Javascript
基于JS实现移动端访问PC端页面时跳转到对应的移动端网页
2020/12/24 Javascript
JS产生随机数的用法小结
2016/12/10 Javascript
Angular指令封装jQuery日期时间插件datetimepicker实现双向绑定示例
2017/01/22 Javascript
angular2模块和共享模块详解
2018/04/08 Javascript
vue1.0和vue2.0的watch监听事件写法详解
2018/09/11 Javascript
详解微信小程序获取当前时间及日期的方法
2019/04/28 Javascript
亲自动手实现vue日历控件
2019/06/26 Javascript
layui实现数据分页功能
2019/07/27 Javascript
在js文件中引入(调用)另一个js文件的三种方法
2020/09/11 Javascript
python中的插值 scipy-interp的实现代码
2018/07/23 Python
python实现植物大战僵尸游戏实例代码
2019/06/10 Python
TensorFlow查看输入节点和输出节点名称方式
2020/01/04 Python
tensorflow实现打印ckpt模型保存下的变量名称及变量值
2020/01/04 Python
英国在线珠宝店:The Jewel Hut
2017/03/20 全球购物
Jacques Lemans德国:奥地利钟表品牌
2019/12/26 全球购物
2014中学教师节广播稿
2014/09/10 职场文书
给老婆道歉的话
2015/01/20 职场文书
就业意向书范本
2015/05/11 职场文书
党小组意见范文
2015/06/08 职场文书
css实现两栏布局,左侧固定宽,右侧自适应的多种方法
2021/08/07 HTML / CSS
mysql实现将字符串字段转为数字排序或比大小
2022/06/14 MySQL