Return a connection with a given alias.
(alias=DEFAULT_CONNECTION_NAME, reconnect=False)
| 306 | |
| 307 | |
| 308 | def get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False): |
| 309 | """Return a connection with a given alias.""" |
| 310 | |
| 311 | # Connect to the database if not already connected |
| 312 | if reconnect: |
| 313 | disconnect(alias) |
| 314 | |
| 315 | # If the requested alias already exists in the _connections list, return |
| 316 | # it immediately. |
| 317 | if alias in _connections: |
| 318 | return _connections[alias] |
| 319 | |
| 320 | # Validate that the requested alias exists in the _connection_settings. |
| 321 | # Raise ConnectionFailure if it doesn't. |
| 322 | if alias not in _connection_settings: |
| 323 | if alias == DEFAULT_CONNECTION_NAME: |
| 324 | msg = "You have not defined a default connection" |
| 325 | else: |
| 326 | msg = 'Connection with alias "%s" has not been defined' % alias |
| 327 | raise ConnectionFailure(msg) |
| 328 | |
| 329 | def _clean_settings(settings_dict): |
| 330 | if PYMONGO_VERSION < (4,): |
| 331 | irrelevant_fields_set = { |
| 332 | "name", |
| 333 | "username", |
| 334 | "password", |
| 335 | "authentication_source", |
| 336 | "authentication_mechanism", |
| 337 | "authmechanismproperties", |
| 338 | } |
| 339 | rename_fields = {} |
| 340 | else: |
| 341 | irrelevant_fields_set = {"name"} |
| 342 | rename_fields = { |
| 343 | "authentication_source": "authSource", |
| 344 | "authentication_mechanism": "authMechanism", |
| 345 | } |
| 346 | return { |
| 347 | rename_fields.get(k, k): v |
| 348 | for k, v in settings_dict.items() |
| 349 | if k not in irrelevant_fields_set and v is not None |
| 350 | } |
| 351 | |
| 352 | raw_conn_settings = _connection_settings[alias].copy() |
| 353 | |
| 354 | # Retrieve a copy of the connection settings associated with the requested |
| 355 | # alias and remove the database name and authentication info (we don't |
| 356 | # care about them at this point). |
| 357 | conn_settings = _clean_settings(raw_conn_settings) |
| 358 | if DriverInfo is not None: |
| 359 | conn_settings.setdefault( |
| 360 | "driver", DriverInfo("MongoEngine", mongoengine.__version__) |
| 361 | ) |
| 362 | |
| 363 | # Determine if we should use PyMongo's or mongomock's MongoClient. |
| 364 | if "mongo_client_class" in conn_settings: |
| 365 | mongo_client_class = conn_settings.pop("mongo_client_class") |