Skip to content

Commit e27f93e

Browse files
committed
Improve performance by caching MongoClient
1 parent 0ac7ca9 commit e27f93e

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

django_mongodb_backend/base.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import contextlib
21
import os
32

43
from django.core.exceptions import ImproperlyConfigured
@@ -88,6 +87,7 @@ class DatabaseWrapper(BaseDatabaseWrapper):
8887
"endswith": "LIKE '%%' || {}",
8988
"iendswith": "LIKE '%%' || UPPER({})",
9089
}
90+
_connections = {}
9191

9292
def _isnull_operator(a, b):
9393
is_null = {
@@ -175,7 +175,12 @@ def get_connection_params(self):
175175

176176
@async_unsafe
177177
def get_new_connection(self, conn_params):
178-
return MongoClient(**conn_params, driver=self._driver_info())
178+
if self.alias not in self._connections:
179+
conn = MongoClient(**conn_params, driver=self._driver_info())
180+
# setdefault() ensures that multiple threads don't set this in
181+
# parallel.
182+
self._connections.setdefault(self.alias, conn)
183+
return self._connections[self.alias]
179184

180185
def _driver_info(self):
181186
if not os.environ.get("RUNNING_DJANGOS_TEST_SUITE"):
@@ -188,15 +193,14 @@ def _commit(self):
188193
def _rollback(self):
189194
pass
190195

196+
def _close(self):
197+
# MongoClient is a connection pool and, unlike database drivers that
198+
# implement PEP 249, shouldn't be closed by connection.close().
199+
pass
200+
191201
def set_autocommit(self, autocommit, force_begin_transaction_with_broken_autocommit=False):
192202
self.autocommit = autocommit
193203

194-
@async_unsafe
195-
def close(self):
196-
super().close()
197-
with contextlib.suppress(AttributeError):
198-
del self.database
199-
200204
@async_unsafe
201205
def cursor(self):
202206
return Cursor()

0 commit comments

Comments
 (0)