2 changed files with 60 additions and 2 deletions
@ -0,0 +1,32 @@ |
|||||
|
# utils/ip_helper.py |
||||
|
import geoip2.database |
||||
|
from django.conf import settings |
||||
|
import os |
||||
|
|
||||
|
|
||||
|
def get_client_ip(request): |
||||
|
"""Retrieves the real IP address from the request.""" |
||||
|
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') |
||||
|
if x_forwarded_for: |
||||
|
# The header contains a list of IPs, the first one is the real client |
||||
|
ip = x_forwarded_for.split(',')[0] |
||||
|
else: |
||||
|
ip = request.META.get('REMOTE_ADDR') |
||||
|
return ip |
||||
|
|
||||
|
def get_country_code(ip_address): |
||||
|
""" |
||||
|
Returns the ISO country code (e.g., 'RU', 'US', 'IR') for an IP. |
||||
|
Returns None if IP is invalid or not found. |
||||
|
""" |
||||
|
# Path to your .mmdb file |
||||
|
db_path = os.path.join(settings.BASE_DIR, 'utils', 'country_city_db', 'GeoLite2-Country.mmdb') |
||||
|
|
||||
|
try: |
||||
|
with geoip2.database.Reader(db_path) as reader: |
||||
|
response = reader.country(ip_address) |
||||
|
return response.country.iso_code |
||||
|
except Exception as e: |
||||
|
# Log error in production |
||||
|
print(f"GeoIP Error: {e}") |
||||
|
return None |
||||
Write
Preview
Loading…
Cancel
Save
Reference in new issue