You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

46 lines
1.3 KiB

# 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."""
if not request:
return None
# Cloudflare header
cf_ip = request.META.get('HTTP_CF_CONNECTING_IP')
if cf_ip:
return cf_ip.strip()
# Nginx / Reverse proxy Real-IP
real_ip = request.META.get('HTTP_X_REAL_IP')
if real_ip:
return real_ip.strip()
# Standard X-Forwarded-For header
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0].strip()
if ip:
return ip
return request.META.get('REMOTE_ADDR')
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