yunojuno / django-geoip2-extras

Additional functionality using the GeoIP2 database and functions.
MIT License
8 stars 4 forks source link

v2: Update library to use cache and request headers #12

Closed hugorodgerbrown closed 3 years ago

hugorodgerbrown commented 3 years ago

This is a complete rework of the existing library, with two major changes:

  1. IP/GeoIP data is stashed in the cache, not the session, and
  2. Data is stored on the request/response as headers, not objects.

The first change is non-breaking - we were caching IP lookup data on the user's session, but given that IP addresses may be shared by users, it makes more sense to stash it in the cache instead.

The second change is a change in how the data is presented. The previous implementation stored the GeoIP data as a Python object on the HttpRequest object. The new implementation stores the information on the request as the raw dict that is returned from MaxMind in an attr called request.geo_data. The same data is also added to the HttpResponse object as header values in the X-GeoIP2-FOO form. e.g. the "country code" would appear as request.geo_data["country_code"], and as the header value X-GeoIP2-Country-Code in the response.

$ curl -I -H "x-forwarded-for: 142.250.180.3" localhost:8000
HTTP/1.1 200 OK
Date: Sun, 29 Aug 2021 15:47:22 GMT
Server: WSGIServer/0.2 CPython/3.9.4
Content-Type: text/html
X-GeoIP2-City:
X-GeoIP2-Continent-Code: NA
X-GeoIP2-Continent-Name: North America
X-GeoIP2-Country-Code: US
X-GeoIP2-Country-Name: United States
X-GeoIP2-Dma-Code:
X-GeoIP2-Is-In-European-Union: False
X-GeoIP2-Latitude: 37.751
X-GeoIP2-Longitude: -97.822
X-GeoIP2-Postal-Code:
X-GeoIP2-Region:
X-GeoIP2-Time-Zone: America/Chicago
X-GeoIP2-Remote-Addr: 142.250.180.3
Content-Length: 10697

This is available from your code via the request.geo_data dict:

>>> request.geo_data
{
    "city": "",
    "continent-code": "NA",
    "continent-name": "North America",
    "country-code": "US",
    "country-name": "United States",
    "dma-code": "",
    "is-in-european-union": False,
    "latitude": 37.751,
    "longitude": -97.822,
    "postal-code": "",
    "region": "",
    "time-zone": "America/Chicago",
    "remote-addr": "142.250.180.3"
}