4

I have the need to test an IPs location during each request. Naturally, this fits nicely with writing a small piece of custom middleware.

Given this is python, is it better to initialize the GeoIP2 instance at the module level or should I initialize it per-request?

I am using django.contrib.gis.geoip2.GeoIP2 which itself uses: https://github.com/maxmind/GeoIP2-python

Specifcially: geoip2.database.Reader()

Looking at the source, first for the django module I see that it has some caching options. I have the libmaxminddb C extension installed and according to the docs in the django source MODE_AUTO = 0 is the default which translates it to trying: MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that order.

Browsing down to the C extension for the database loading:

https://github.com/maxmind/MaxMind-DB-Reader-python/blob/master/maxminddb/extension/maxminddb.c

It seems to me that the file is not held in memory, which makes perfect sense as that would be an unexpected side effect for anyone using it. That also begs the question:

Given that it looks like the mmdb file it's loaded each time GeoIP2 is called/initialized, and since the local database does not change does it make more sense to initialize GeoIP2 at the module level since every request, in my use case, needs it and by initializing at the module level I would save myself the I/O of reading the file initially each request?

Or should I leave it to be initialized per request and change the caching option to something like MODE_MEMORY?

4

0 回答 0