Skip to content

Instantly share code, notes, and snippets.

@uda
Created August 18, 2017 10:06
Show Gist options
  • Select an option

  • Save uda/1bc43041f889cf4256fe5288e8e4dac5 to your computer and use it in GitHub Desktop.

Select an option

Save uda/1bc43041f889cf4256fe5288e8e4dac5 to your computer and use it in GitHub Desktop.

Revisions

  1. uda created this gist Aug 18, 2017.
    21 changes: 21 additions & 0 deletions django_remote_addr.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    from django.conf import settings
    from django.views.generic import View


    class SomeBaseView(View):
    _ip_address = None

    def django_ip_address(self):
    if self._ip_address is None:
    x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR') or ''
    if x_forwarded_for.strip():
    ip_list = [single_ip.strip() for single_ip in x_forwarded_for.split(',')]
    ip_list.reverse()
    ip = None
    for ip in ip_list:
    if ip not in settings.PROXY_SERVERS:
    break
    self._ip_address = ip
    if not self._ip_address:
    self._ip_address = self.request.META.get('REMOTE_ADDR', '')
    return self._ip_address
    8 changes: 8 additions & 0 deletions settings.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    """
    Example of known internal proxies to ignore
    """

    PROXY_SERVERS = (
    '10.4.40.3',
    '172.23.23.5',
    )