How do I get user IP address in django?

后端 未结 11 1364
野趣味
野趣味 2020-11-22 15:33

How do I get user\'s IP in django?

I have a view like this:

# Create your views
from django.contrib.gis.utils import GeoIP
from django.template impor         


        
11条回答
  •  旧巷少年郎
    2020-11-22 16:27

    You can use django-ipware which supports Python 2 & 3 and handles IPv4 & IPv6.

    Install:

    pip install django-ipware

    Simple Usage:

    # In a view or a middleware where the `request` object is available
    
    from ipware import get_client_ip
    ip, is_routable = get_client_ip(request)
    if 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
    
    # Order of precedence is (Public, Private, Loopback, None)
    

    Advanced Usage:

    • Custom Header - Custom request header for ipware to look at:

      i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR'])
      i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR', 'REMOTE_ADDR'])
      
    • Proxy Count - Django server is behind a fixed number of proxies:

      i, r = get_client_ip(request, proxy_count=1)
      
    • Trusted Proxies - Django server is behind one or more known & trusted proxies:

      i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2'))
      
      # For multiple proxies, simply add them to the list
      i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2', '177.3.3.3'))
      
      # For proxies with fixed sub-domain and dynamic IP addresses, use partial pattern
      i, r = get_client_ip(request, proxy_trusted_ips=('177.2.', '177.3.'))
      

    Note: read this notice.

提交回复
热议问题