I
I
Ilya Korol2019-07-04 17:30:35
Django
Ilya Korol, 2019-07-04 17:30:35

How to get location by IP?

There is an IP. It is necessary to determine the approximate location on it, preferably without using third-party services. When connecting to the site, the server must determine the approximate location of the user.
It is necessary to determine the points where the service is more popular.
It is clear that it will be used in the majority near cities, especially large ones, but it needs to be determined. If in some city, then the name of the city and its coordinates, if the village - the name of the village and its coordinates.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew, 2019-07-04
@welcome32

Use https://github.com/maxmind/GeoIP2-python
It can be used locally without requests to a third party API

spoiler
>>> import geoip2.database
>>>
>>> # This creates a Reader object. You should use the same object
>>> # across multiple requests as creation of it is expensive.
>>> reader = geoip2.database.Reader('/path/to/GeoLite2-City.mmdb')
>>>
>>> # Replace "city" with the method corresponding to the database
>>> # that you are using, e.g., "country".
>>> response = reader.city('128.101.101.101')
>>>
>>> response.country.iso_code
'US'
>>> response.country.name
'United States'
>>> response.country.names['zh-CN']
u'美国'
>>>
>>> response.subdivisions.most_specific.name
'Minnesota'
>>> response.subdivisions.most_specific.iso_code
'MN'
>>>
>>> response.city.name
'Minneapolis'
>>>
>>> response.postal.code
'55455'
>>>
>>> response.location.latitude
44.9733
>>> response.location.longitude
-93.2323
>>> reader.close()

This module is built into Django https://docs.djangoproject.com/en/2.2/ref/contrib/...
spoiler
>>> from django.contrib.gis.geoip2 import GeoIP2
>>> g = GeoIP2()
>>> g.country('google.com')
{'country_code': 'US', 'country_name': 'United States'}
>>> g.city('72.14.207.99')
{'city': 'Mountain View',
'country_code': 'US',
'country_name': 'United States',
'dma_code': 807,
'latitude': 37.419200897216797,
'longitude': -122.05740356445312,
'postal_code': '94043',
'region': 'CA'}
>>> g.lat_lon('salon.com')
(39.0437, -77.4875)
>>> g.lon_lat('uh.edu')
(-95.4342, 29.834)
>>> g.geos('24.124.1.80').wkt
'POINT (-97 38)'

G
Gomonov, 2019-07-04
@Gomonov

Not everything is so simple, especially with mobile Internet. For example, I am in Bryansk, and if I am on my mobile phone, my ip is Moscow. It has long been over 50% for mobile traffic, so in most cases, geo by ip is not determined accurately. Of course, in the mass scale of countries, everything is ok.
If you answer specifically to your question, then the maxmind bases will help. They have paid and free ones.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question