Close the connection with a given alias.
(alias=DEFAULT_CONNECTION_NAME)
| 273 | |
| 274 | |
| 275 | def disconnect(alias=DEFAULT_CONNECTION_NAME): |
| 276 | """Close the connection with a given alias.""" |
| 277 | from mongoengine import Document |
| 278 | from mongoengine.base.common import _get_documents_by_db |
| 279 | |
| 280 | connection = _connections.pop(alias, None) |
| 281 | if connection: |
| 282 | # MongoEngine may share the same MongoClient across multiple aliases |
| 283 | # if connection settings are the same so we only close |
| 284 | # the client if we're removing the final reference. |
| 285 | # Important to use 'is' instead of '==' because clients connected to the same cluster |
| 286 | # will compare equal even with different options |
| 287 | if all(connection is not c for c in _connections.values()): |
| 288 | connection.close() |
| 289 | |
| 290 | if alias in _dbs: |
| 291 | # Detach all cached collections in Documents |
| 292 | for doc_cls in _get_documents_by_db(alias, DEFAULT_CONNECTION_NAME): |
| 293 | if issubclass(doc_cls, Document): # Skip EmbeddedDocument |
| 294 | doc_cls._disconnect() |
| 295 | |
| 296 | del _dbs[alias] |
| 297 | |
| 298 | if alias in _connection_settings: |
| 299 | del _connection_settings[alias] |
| 300 | |
| 301 | |
| 302 | def disconnect_all(): |