Created
August 18, 2017 10:06
-
-
Save uda/1bc43041f889cf4256fe5288e8e4dac5 to your computer and use it in GitHub Desktop.
Django Remote IP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Example of known internal proxies to ignore | |
| """ | |
| PROXY_SERVERS = ( | |
| '10.4.40.3', | |
| '172.23.23.5', | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment