简体   繁体   English

在Django中设置全局变量

[英]Setting up a global variable in django

I am using elasticsearch and need to set up a persistent connection to it which I resuse anywhere in my project. 我正在使用elasticsearch,需要建立与它的持久连接,我可以在项目的任何地方重用它。 However, after much digging I am still unsure how to properly create a global var which I can be sure will only be instantiated once. 但是,经过大量的挖掘之后,我仍然不确定如何正确创建一个全局变量,我可以确定它只会被实例化一次。 I have created the following file: 我创建了以下文件:

es.py es.py

from elasticsearch import Elasticsearch
es = Elasticsearch()

I use it in places like tasks and views as follows: 我在任务和视图之类的地方使用它,如下所示:

import es
es.es.search(***********)

But to me it seems this would merely call es = Elasticsearch() each time, resulting in the connection being recreated. 但是在我看来,这每次只会调用es = Elasticsearch() ,从而导致重新创建连接。 Is my approach correct? 我的方法正确吗?

Regardless of the choice of module and variable names ( es.es seems awkward), what your doing seems ok. 无论选择模块名和变量名( es.es看起来都很尴尬),您所做的事情似乎都可以。

Elasticsearch() will be called only once, no matter how many times you import the module in the rest of your code. 无论您在其余代码中将模块导入多少次, Elasticsearch()都只会被调用一次。

I think you would want some way of reconnecting if the connection is lost, but that is another matter. 我认为如果连接断开,您将需要某种重新连接的方法,但这是另一回事。

It should be correct as when you import es , es.py is executed and all the variables are initialized and added to the context. 它应该是正确的,因为在import es ,将执行 es.py并将所有变量初始化并添加到上下文中。 So, using es.es.search would use the already initialized variable es . 因此,使用es.es.search使用已经初始化的变量es

Just put this code in your settings.py file. 只需将这段代码放在您的settings.py文件中即可。 Django will run it once and your connection will be instantiated once. Django将运行一次,并且您的连接将被实例化一次。 And then import it from settings like this: 然后从这样的设置中导入它:

from django.conf import settings
settings.es

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM