本文介绍了Django中MaxMind GeoIP2单实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为MaxMind的GeoIP数据库使用python wrapper'geoip2'。在文档中说,您应该仅创建数据库读取器的单个实例,因为打开数据库非常昂贵,当然,为每个请求打开它是一个非常糟糕的主意。

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.

所以,如果我的服务器上有Django(1.10)+ Gunicorn,我应该如何创建数据库阅读器的单身?这通常不是关于geoip2模块的问题,这是一个问题:

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:


  1. 如何创建单个对象,可从应用程序访问(不是
    整个项目)?可以在 __ init __ 中执行类似的操作: os.environ ['APP_VAR_WHATEVER'] = InitObject()

  1. How should I create a single object, accessible from the app (notthe whole project)? Is it OK to do something like this in __init__: os.environ['APP_VAR_WHATEVER'] = InitObject()?

不幸的是,我对Gunicorn不太了解,所以第二个
的问题是:工作多长时间?是否每N
分钟/秒重启?我在问这个问题,因为我担心如果
经常重新启动工作人员,那么会产生额外的不必要的
系统负载。

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. 如上所述,您可以实现单例模式,以便只有一个数据库读取器应该缓存数据库在内存中,以便更快地进行查询(例如,查询词典比数据库对象便宜)。

  2. 还有几个秒钟内保持非活动状态的爆米哥运动员默认为30秒),但您可以配置值来为您的如果您的工作人员保持沉默很长时间,并且您不希望它经常重新启动,则需要。

  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).
  2. 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.

这里是Singleton模式的有用示例

Here http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html is a helpful example of the Singleton Pattern

这篇关于Django中MaxMind GeoIP2单实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:46
查看更多