欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-30 21:56:46
本文实例讲述了python django框架应用中实现获取访问者ip地址。分享给大家供大家参考,具体如下: 在django官方文档中有一段对request.meta的解释...

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

ps:这里再为大家推荐一款功能相似的在线工具供大家参考:

ip地址归属地在线查询工具:

另外,本站在线工具小程序上也有一款功能更加强大的ip地址解析工具,感兴趣的朋友可以扫描如下小程序码查看:

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

希望本文所述对大家基于django框架的python程序设计有所帮助。