Django应用用于识别客户端 IP 地址的包django-ipware

django-ipware为Django应用程序用于识别客户端 IP 地址的包。

支持 Python 2 和 3 并处理 IPv4 和 IPv6。

1.安装

pip install django-ipware

2.简单实用

 # In a view or a middleware where the `request` object is available

 from ipware import get_client_ip
 client_ip, is_routable = get_client_ip(request)
 if client_ip is None:
    # Unable to get the client's IP address
 else:
     # We got the client's IP address
     if is_routable:
         # The client's IP address is publicly routable on the Internet
     else:
         # The client's IP address is private

3.高级用法

通过在settings.py添加IPWARE_META_PRECEDENCE_ORDER来调整优先级顺序

 # The default meta precedence order (update as needed)
 IPWARE_META_PRECEDENCE_ORDER = (
      "X_FORWARDED_FOR",  # AWS ELB (default client is `left-most` [`<client>, <proxy1>, <proxy2>`])
      "HTTP_X_FORWARDED_FOR",  # Similar to X_FORWARDED_TO
      "HTTP_CLIENT_IP",  # Standard headers used by providers such as Amazon EC2, Heroku etc.
      "HTTP_X_REAL_IP",  # Standard headers used by providers such as Amazon EC2, Heroku etc.
      "HTTP_X_FORWARDED",  # Squid and others
      "HTTP_X_CLUSTER_CLIENT_IP",  # Rackspace LB and Riverbed Stingray
      "HTTP_FORWARDED_FOR",  # RFC 7239
      "HTTP_FORWARDED",  # RFC 7239
      "HTTP_VIA",  # Squid and others
      "X-CLIENT-IP",  # Microsoft Azure
      "X-REAL-IP",  # NGINX
      "X-CLUSTER-CLIENT-IP",  # Rackspace Cloud Load Balancers
      "X_FORWARDED",  # Squid
      "FORWARDED_FOR",  # RFC 7239
      "CF-CONNECTING-IP",  # CloudFlare
      "TRUE-CLIENT-IP",  # CloudFlare Enterprise,
      "FASTLY-CLIENT-IP",  # Firebase, Fastly
      "FORWARDED",  # RFC 7239
      "CLIENT-IP",  # Akamai and Cloudflare: True-Client-IP and Fastly: Fastly-Client-IP
      "REMOTE_ADDR",  # Default
  )
  • ipware 要查看的自定义请求标头
get_client_ip(request, request_header_order=['X_FORWARDED_FOR'])
get_client_ip(request, request_header_order=['X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR'])

代理计数 - Django 服务器在固定数量的代理后面:

i, r = get_client_ip(request, proxy_count=1)

如果更喜欢一个不直接与 Django 集成的纯 python 版本,可以改用python-ipware包。

参考资料

项目github:https://github.com/un33k/django-ipware