非反代情况下Django 中 ip = request.META['REMOTE_ADDR'] 即可拿到对应ip地址

Nginx、fcgi、uwsgi等反代情况下

vi /etc/nginx/conf.d/xxx.conf 加入下面几行

location / {

proxy_pass http://127.0.0.1:8080;

proxy_redirect off;

     proxy_set_header        Host    $host;

proxy_set_header        REMOTE_ADDR     $remote_addr;

proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

   real_ip_recursive on;

}

完整Nginx配置模板

 server {
listen 80;
server_name xxx;
access_log /var/log/nginx/xxx.access_log;
error_log /var/log/nginx/xxx.error_log; location /static/ {
alias /data/vhost/xxx/static/;
expires 30d;
} location / {
proxy_pass http://127.0.0.1:8080;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header REMOTE_ADDR $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
real_ip_recursive on;
proxy_max_temp_file_size 0;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}
}

xxx.conf

Django对应功能模块儿目录下views.py加入

 def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
return ip

views.py

需要时请求此函数即可

ip = get_client_ip(request)

另外ip整数和点分十进制转换函数附上(pip install inet_ntoa)

 def long2ip(ip):
return inet_ntoa(pack("!L", ip))

long2ip

 def ip2long(ip):
"""
Convert an IP string to long
"""
packedIP = socket.inet_aton(ip)
return struct.unpack("!L", packedIP)[0]

ip2long

由ip地址获得所在地

 def come_from(ip):
r = requests.get(url='http://freegeoip.net/json/%s' % ip)
return r.json()

come_from

05-06 17:54