Hello,
We are selling different products in different countries from local
organisations. I therefore have to know from which country somebody is
accessing the shop and propose him the right payment module and right
products.
I have written some code , but since I am quite new to django
development I wonder whether the approach was a correct one and
somebody can propose "better" ways.
In order to dtermine the country I rely on the maxmind service.
Reverse geocoding is done utilising the google maps API
1. I have a defined a model to store IP adresses so that I do not have
to utilise maxmind for known IP's :
class IP(models.Model):
ip = models.CharField(max_length=15) # IP adress
extracted from the logfile or from forms
creation_date = models.DateTimeField('date first
access',default=datetime.datetime.now)
last_access = models.DateTimeField('last
access',default=datetime.datetime.now)
country = models.CharField(max_length=50, blank=True) #
country
region = models.CharField(max_length=50, blank=True) #
region
city = models.CharField(max_length=60, blank = True) # city
street = models.CharField(max_length=80, blank = True)
x = models.FloatField(default=0)
# coordinates
y = models.FloatField(default=0)
count = models.IntegerField(default=0)
company = models.CharField(max_length=80, blank = True)
class Meta:
verbose_name = "IP"
verbose_name_plural = "IPs"
def __unicode__(self):
return self.ip
def adress(self):
return {"street" : self.street , "city" : self.city,
"country" : self.country }
def coordinates(self):
return {"x" : self.x, "y" : self.y}
class IPAdmin(admin.ModelAdmin) :
list_display = ('ip','country', 'region','city')
2. written some code to get the country and more detailed adress data
(behind and without proxy)
def geoip(ip) :
keys = ("country", "region",
"city","zip","x","y","param1","param2","provider1","provider2")
url = 'http://geoip3.maxmind.com/f?l=' + MAXMIND_API + '&i=' +
str(ip)
try :
response = urllib2.urlopen(url).read().split(",")
except :
pass
result ={}
for i,key in enumerate(keys) :
result[key] = response[i].decode('ISO-8859-1').encode('utf-8')
return result
def reverse_geoip(x,y):
keys = ("street","city", "country")
gmaps = GoogleMaps(GOOGLE_MAPS_API)
destination = gmaps.latlng_to_address(float(x),
float(y)).split(",")
result ={}
for i,key in enumerate(keys) :
try :
result[key] = destination[i]
except :
result[key] = "unknown"
return result
def IP_save(ip):
try :
visitor = IP.objects.get(ip=ip)
visitor.count += 1
visitor.last_access = datetime.datetime.now()
visitor.save()
except IP.DoesNotExist :
coordinates = geoip(ip)
if (coordinates["x"] != "" and coordinates["y"] != "" ) :
adress = reverse_geoip(coordinates["x"], coordinates["y"])
visitor = IP(ip=ip,
country = adress["country"],
city = adress["city"],
street = adress["street"],
x = coordinates["x"],
y = coordinates["y"],
company =
coordinates["provider1"] )
visitor.save()
else :
visitor = IP(ip="127.0.0.1",
country = DEFAULT_COUNTRY,
city = DEFAULT_CITY,
street = "HQ",
x = 0,
y = 0 ,
company = "internal")
visitor.save()
return visitor
def current_IP(request):
try :
ip = request.META['HTTP_X_FORWARDED_FOR'].split(",")[0]
except :
ip = request.META['REMOTE_ADDR']
try :
ip = IP.objects.get(ip=ip)
except IP.DoesNotExist:
ip = IP_save(ip)
return ip
3. add a template processor to add language data and country/location
data to the template. This variables can be used in the templates to
show country/location dependent content
def localit(request):
"""
adds information based on IP adress and reverse Geocoding to the
site
"""
ip = current_IP(request)
visitor = IP_save(ip)
countries = GasCountry.objects.all()
country = visitor.country[1:]
cl = []
found = False
for c in countries :
if c.country.lower() == country.lower() :
found = True
cl.append(c.country)
if not found :
country = DEFAULT_COUNTRY
trans = translation.get_language()
return { "IP" : ip.ip ,
"COUNTRY" : country,
"CITY" : visitor.city ,
"X" : visitor.x ,
"Y" : visitor.y ,
"COUNTRIES" : cl ,
"CLANG" : trans + country ,
"LANGUAGE" : trans
}
--
You received this message because you are subscribed to the Google Groups
"Satchmo users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/satchmo-users?hl=en.