问题
I'm using python wrapper 'geoip2' for MaxMind's GeoIP database. It's said in the docs that you should create only single instance of the database reader, because opening the database is very expensive, and, of course, opening it for every request is a very bad idea.
So, if I have Django (1.10) + Gunicorn on my server, how should I create the "singleton" of the database reader? That's generally not a question about geoip2 module, it's question about:
How should I create a single object, accessible from the app (not the whole project)? Is it OK to do something like this in
__init__
:os.environ['APP_VAR_WHATEVER'] = InitObject()
?Unfortunately, I don't know much about Gunicorn, so the second question is: how long does worker live? Is it restarting every N minutes/seconds? I'm asking this question because I'm afraid if it respawns workers too often, it would create additional unwanted system load.
回答1:
- As you mentioned, you can implement a singleton pattern in order to have only one database reader which should cache the database in memory in order to make queries faster (for example, it is less expensive to query a dictionary than a database object).
- Gunicorn workers that stay inactive more than a number of seconds (default is 30s) but you can configure the timeout value to serve your needs if your worker stays silent for great periods of time and you don't want it to restart often.
Here http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html is a helpful example of the Singleton Pattern
来源:https://stackoverflow.com/questions/42358525/maxmind-geoip2-single-instance-in-django