RunLoop
RunLoop

Reputation: 20376

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

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. Is my approach correct?

Upvotes: 1

Views: 1899

Answers (3)

Sebastian
Sebastian

Reputation: 2877

Regardless of the choice of module and variable names (es.es seems awkward), what your doing seems ok.

Elasticsearch() will be called only once, no matter how many times you import the module in the rest of your code.

I think you would want some way of reconnecting if the connection is lost, but that is another matter.

Upvotes: 4

ForceBru
ForceBru

Reputation: 44830

It should be correct as when you import es, es.py is executed and all the variables are initialized and added to the context. So, using es.es.search would use the already initialized variable es.

Upvotes: 2

Nick
Nick

Reputation: 1194

Just put this code in your settings.py file. Django will run it once and your connection will be instantiated once. And then import it from settings like this:

from django.conf import settings
settings.es

Upvotes: 2

Related Questions