1
- import contextlib
2
1
import os
3
2
4
3
from django .core .exceptions import ImproperlyConfigured
@@ -88,6 +87,7 @@ class DatabaseWrapper(BaseDatabaseWrapper):
88
87
"endswith" : "LIKE '%%' || {}" ,
89
88
"iendswith" : "LIKE '%%' || UPPER({})" ,
90
89
}
90
+ _connections = {}
91
91
92
92
def _isnull_operator (a , b ):
93
93
is_null = {
@@ -175,7 +175,12 @@ def get_connection_params(self):
175
175
176
176
@async_unsafe
177
177
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 ]
179
184
180
185
def _driver_info (self ):
181
186
if not os .environ .get ("RUNNING_DJANGOS_TEST_SUITE" ):
@@ -188,15 +193,14 @@ def _commit(self):
188
193
def _rollback (self ):
189
194
pass
190
195
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
+
191
201
def set_autocommit (self , autocommit , force_begin_transaction_with_broken_autocommit = False ):
192
202
self .autocommit = autocommit
193
203
194
- @async_unsafe
195
- def close (self ):
196
- super ().close ()
197
- with contextlib .suppress (AttributeError ):
198
- del self .database
199
-
200
204
@async_unsafe
201
205
def cursor (self ):
202
206
return Cursor ()
0 commit comments