We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Connection pooling with mongoengine
Hi,
   Kindly assist, if there is any way to configure connection pool in mongo engine maybe in connect function or through some other way.
  In case we are using default connection pool of pymongo, kindly clarify about the same.

  Also, i observed a certain behavior after testing my django app with mongo using mongoengine. With some random number of hits, it opens a new connection and keeps that open. I made about 50 requests and 11 new connections were opened and neither of them was closed. In my first 7 requests, every time a new connection was established. Since every request was sequential, shouldn't it use previous connection object in-spite of creating one.

 A decent clarification will be helpful. This is the first time i am using mongoengine.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mongoengine/connection.py`
Content:
```
1 from pymongo import MongoClient, ReadPreference, uri_parser
2 import six
3 
4 from mongoengine.python_support import IS_PYMONGO_3
5 
6 __all__ = ['MongoEngineConnectionError', 'connect', 'register_connection',
7            'DEFAULT_CONNECTION_NAME']
8 
9 
10 DEFAULT_CONNECTION_NAME = 'default'
11 
12 if IS_PYMONGO_3:
13     READ_PREFERENCE = ReadPreference.PRIMARY
14 else:
15     from pymongo import MongoReplicaSetClient
16     READ_PREFERENCE = False
17 
18 
19 class MongoEngineConnectionError(Exception):
20     """Error raised when the database connection can't be established or
21     when a connection with a requested alias can't be retrieved.
22     """
23     pass
24 
25 
26 _connection_settings = {}
27 _connections = {}
28 _dbs = {}
29 
30 
31 def register_connection(alias, name=None, host=None, port=None,
32                         read_preference=READ_PREFERENCE,
33                         username=None, password=None,
34                         authentication_source=None,
35                         authentication_mechanism=None,
36                         **kwargs):
37     """Add a connection.
38 
39     :param alias: the name that will be used to refer to this connection
40         throughout MongoEngine
41     :param name: the name of the specific database to use
42     :param host: the host name of the :program:`mongod` instance to connect to
43     :param port: the port that the :program:`mongod` instance is running on
44     :param read_preference: The read preference for the collection
45        ** Added pymongo 2.1
46     :param username: username to authenticate with
47     :param password: password to authenticate with
48     :param authentication_source: database to authenticate against
49     :param authentication_mechanism: database authentication mechanisms.
50         By default, use SCRAM-SHA-1 with MongoDB 3.0 and later,
51         MONGODB-CR (MongoDB Challenge Response protocol) for older servers.
52     :param is_mock: explicitly use mongomock for this connection
53         (can also be done by using `mongomock://` as db host prefix)
54     :param kwargs: allow ad-hoc parameters to be passed into the pymongo driver
55 
56     .. versionchanged:: 0.10.6 - added mongomock support
57     """
58     conn_settings = {
59         'name': name or 'test',
60         'host': host or 'localhost',
61         'port': port or 27017,
62         'read_preference': read_preference,
63         'username': username,
64         'password': password,
65         'authentication_source': authentication_source,
66         'authentication_mechanism': authentication_mechanism
67     }
68 
69     conn_host = conn_settings['host']
70 
71     # Host can be a list or a string, so if string, force to a list.
72     if isinstance(conn_host, six.string_types):
73         conn_host = [conn_host]
74 
75     resolved_hosts = []
76     for entity in conn_host:
77 
78         # Handle Mongomock
79         if entity.startswith('mongomock://'):
80             conn_settings['is_mock'] = True
81             # `mongomock://` is not a valid url prefix and must be replaced by `mongodb://`
82             resolved_hosts.append(entity.replace('mongomock://', 'mongodb://', 1))
83 
84         # Handle URI style connections, only updating connection params which
85         # were explicitly specified in the URI.
86         elif '://' in entity:
87             uri_dict = uri_parser.parse_uri(entity)
88             resolved_hosts.append(entity)
89 
90             if uri_dict.get('database'):
91                 conn_settings['name'] = uri_dict.get('database')
92 
93             for param in ('read_preference', 'username', 'password'):
94                 if uri_dict.get(param):
95                     conn_settings[param] = uri_dict[param]
96 
97             uri_options = uri_dict['options']
98             if 'replicaset' in uri_options:
99                 conn_settings['replicaSet'] = uri_options['replicaset']
100             if 'authsource' in uri_options:
101                 conn_settings['authentication_source'] = uri_options['authsource']
102             if 'authmechanism' in uri_options:
103                 conn_settings['authentication_mechanism'] = uri_options['authmechanism']
104         else:
105             resolved_hosts.append(entity)
106     conn_settings['host'] = resolved_hosts
107 
108     # Deprecated parameters that should not be passed on
109     kwargs.pop('slaves', None)
110     kwargs.pop('is_slave', None)
111 
112     conn_settings.update(kwargs)
113     _connection_settings[alias] = conn_settings
114 
115 
116 def disconnect(alias=DEFAULT_CONNECTION_NAME):
117     """Close the connection with a given alias."""
118     if alias in _connections:
119         get_connection(alias=alias).close()
120         del _connections[alias]
121     if alias in _dbs:
122         del _dbs[alias]
123 
124 
125 def get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
126     """Return a connection with a given alias."""
127 
128     # Connect to the database if not already connected
129     if reconnect:
130         disconnect(alias)
131 
132     # If the requested alias already exists in the _connections list, return
133     # it immediately.
134     if alias in _connections:
135         return _connections[alias]
136 
137     # Validate that the requested alias exists in the _connection_settings.
138     # Raise MongoEngineConnectionError if it doesn't.
139     if alias not in _connection_settings:
140         if alias == DEFAULT_CONNECTION_NAME:
141             msg = 'You have not defined a default connection'
142         else:
143             msg = 'Connection with alias "%s" has not been defined' % alias
144         raise MongoEngineConnectionError(msg)
145 
146     def _clean_settings(settings_dict):
147         irrelevant_fields = set([
148             'name', 'username', 'password', 'authentication_source',
149             'authentication_mechanism'
150         ])
151         return {
152             k: v for k, v in settings_dict.items()
153             if k not in irrelevant_fields
154         }
155 
156     # Retrieve a copy of the connection settings associated with the requested
157     # alias and remove the database name and authentication info (we don't
158     # care about them at this point).
159     conn_settings = _clean_settings(_connection_settings[alias].copy())
160 
161     # Determine if we should use PyMongo's or mongomock's MongoClient.
162     is_mock = conn_settings.pop('is_mock', False)
163     if is_mock:
164         try:
165             import mongomock
166         except ImportError:
167             raise RuntimeError('You need mongomock installed to mock '
168                                'MongoEngine.')
169         connection_class = mongomock.MongoClient
170     else:
171         connection_class = MongoClient
172 
173         # For replica set connections with PyMongo 2.x, use
174         # MongoReplicaSetClient.
175         # TODO remove this once we stop supporting PyMongo 2.x.
176         if 'replicaSet' in conn_settings and not IS_PYMONGO_3:
177             connection_class = MongoReplicaSetClient
178             conn_settings['hosts_or_uri'] = conn_settings.pop('host', None)
179 
180             # hosts_or_uri has to be a string, so if 'host' was provided
181             # as a list, join its parts and separate them by ','
182             if isinstance(conn_settings['hosts_or_uri'], list):
183                 conn_settings['hosts_or_uri'] = ','.join(
184                     conn_settings['hosts_or_uri'])
185 
186             # Discard port since it can't be used on MongoReplicaSetClient
187             conn_settings.pop('port', None)
188 
189     # Iterate over all of the connection settings and if a connection with
190     # the same parameters is already established, use it instead of creating
191     # a new one.
192     existing_connection = None
193     connection_settings_iterator = (
194         (db_alias, settings.copy())
195         for db_alias, settings in _connection_settings.items()
196     )
197     for db_alias, connection_settings in connection_settings_iterator:
198         connection_settings = _clean_settings(connection_settings)
199         if conn_settings == connection_settings and _connections.get(db_alias):
200             existing_connection = _connections[db_alias]
201             break
202 
203     # If an existing connection was found, assign it to the new alias
204     if existing_connection:
205         _connections[alias] = existing_connection
206     else:
207         # Otherwise, create the new connection for this alias. Raise
208         # MongoEngineConnectionError if it can't be established.
209         try:
210             _connections[alias] = connection_class(**conn_settings)
211         except Exception as e:
212             raise MongoEngineConnectionError(
213                 'Cannot connect to database %s :\n%s' % (alias, e))
214 
215     return _connections[alias]
216 
217 
218 def get_db(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
219     if reconnect:
220         disconnect(alias)
221 
222     if alias not in _dbs:
223         conn = get_connection(alias)
224         conn_settings = _connection_settings[alias]
225         db = conn[conn_settings['name']]
226         auth_kwargs = {'source': conn_settings['authentication_source']}
227         if conn_settings['authentication_mechanism'] is not None:
228             auth_kwargs['mechanism'] = conn_settings['authentication_mechanism']
229         # Authenticate if necessary
230         if conn_settings['username'] and (conn_settings['password'] or
231                                           conn_settings['authentication_mechanism'] == 'MONGODB-X509'):
232             db.authenticate(conn_settings['username'], conn_settings['password'], **auth_kwargs)
233         _dbs[alias] = db
234     return _dbs[alias]
235 
236 
237 def connect(db=None, alias=DEFAULT_CONNECTION_NAME, **kwargs):
238     """Connect to the database specified by the 'db' argument.
239 
240     Connection settings may be provided here as well if the database is not
241     running on the default port on localhost. If authentication is needed,
242     provide username and password arguments as well.
243 
244     Multiple databases are supported by using aliases.  Provide a separate
245     `alias` to connect to a different instance of :program:`mongod`.
246 
247     .. versionchanged:: 0.6 - added multiple database support.
248     """
249     if alias not in _connections:
250         register_connection(alias, db, **kwargs)
251 
252     return get_connection(alias)
253 
254 
255 # Support old naming convention
256 _get_connection = get_connection
257 _get_db = get_db
258
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mongoengine/connection.py b/mongoengine/connection.py
--- a/mongoengine/connection.py
+++ b/mongoengine/connection.py
@@ -51,7 +51,9 @@
         MONGODB-CR (MongoDB Challenge Response protocol) for older servers.
     :param is_mock: explicitly use mongomock for this connection
         (can also be done by using `mongomock://` as db host prefix)
-    :param kwargs: allow ad-hoc parameters to be passed into the pymongo driver
+    :param kwargs: ad-hoc parameters to be passed into the pymongo driver,
+        for example maxpoolsize, tz_aware, etc. See the documentation
+        for pymongo's `MongoClient` for a full list.
 
     .. versionchanged:: 0.10.6 - added mongomock support
     """
@@ -241,9 +243,12 @@
     running on the default port on localhost. If authentication is needed,
     provide username and password arguments as well.
 
-    Multiple databases are supported by using aliases.  Provide a separate
+    Multiple databases are supported by using aliases. Provide a separate
     `alias` to connect to a different instance of :program:`mongod`.
 
+    See the docstring for `register_connection` for more details about all
+    supported kwargs.
+
     .. versionchanged:: 0.6 - added multiple database support.
     """
     if alias not in _connections:

{"golden_diff": "diff --git a/mongoengine/connection.py b/mongoengine/connection.py\n--- a/mongoengine/connection.py\n+++ b/mongoengine/connection.py\n@@ -51,7 +51,9 @@\n         MONGODB-CR (MongoDB Challenge Response protocol) for older servers.\n     :param is_mock: explicitly use mongomock for this connection\n         (can also be done by using `mongomock://` as db host prefix)\n-    :param kwargs: allow ad-hoc parameters to be passed into the pymongo driver\n+    :param kwargs: ad-hoc parameters to be passed into the pymongo driver,\n+        for example maxpoolsize, tz_aware, etc. See the documentation\n+        for pymongo's `MongoClient` for a full list.\n \n     .. versionchanged:: 0.10.6 - added mongomock support\n     \"\"\"\n@@ -241,9 +243,12 @@\n     running on the default port on localhost. If authentication is needed,\n     provide username and password arguments as well.\n \n-    Multiple databases are supported by using aliases.  Provide a separate\n+    Multiple databases are supported by using aliases. Provide a separate\n     `alias` to connect to a different instance of :program:`mongod`.\n \n+    See the docstring for `register_connection` for more details about all\n+    supported kwargs.\n+\n     .. versionchanged:: 0.6 - added multiple database support.\n     \"\"\"\n     if alias not in _connections:\n", "issue": "Connection pooling with mongoengine\nHi,\n   Kindly assist, if there is any way to configure connection pool in mongo engine maybe in connect function or through some other way.\n  In case we are using default connection pool of pymongo, kindly clarify about the same.\n\n  Also, i observed a certain behavior after testing my django app with mongo using mongoengine. With some random number of hits, it opens a new connection and keeps that open. I made about 50 requests and 11 new connections were opened and neither of them was closed. In my first 7 requests, every time a new connection was established. Since every request was sequential, shouldn't it use previous connection object in-spite of creating one.\n\n A decent clarification will be helpful. This is the first time i am using mongoengine.\n\n", "before_files": [{"content": "from pymongo import MongoClient, ReadPreference, uri_parser\nimport six\n\nfrom mongoengine.python_support import IS_PYMONGO_3\n\n__all__ = ['MongoEngineConnectionError', 'connect', 'register_connection',\n           'DEFAULT_CONNECTION_NAME']\n\n\nDEFAULT_CONNECTION_NAME = 'default'\n\nif IS_PYMONGO_3:\n    READ_PREFERENCE = ReadPreference.PRIMARY\nelse:\n    from pymongo import MongoReplicaSetClient\n    READ_PREFERENCE = False\n\n\nclass MongoEngineConnectionError(Exception):\n    \"\"\"Error raised when the database connection can't be established or\n    when a connection with a requested alias can't be retrieved.\n    \"\"\"\n    pass\n\n\n_connection_settings = {}\n_connections = {}\n_dbs = {}\n\n\ndef register_connection(alias, name=None, host=None, port=None,\n                        read_preference=READ_PREFERENCE,\n                        username=None, password=None,\n                        authentication_source=None,\n                        authentication_mechanism=None,\n                        **kwargs):\n    \"\"\"Add a connection.\n\n    :param alias: the name that will be used to refer to this connection\n        throughout MongoEngine\n    :param name: the name of the specific database to use\n    :param host: the host name of the :program:`mongod` instance to connect to\n    :param port: the port that the :program:`mongod` instance is running on\n    :param read_preference: The read preference for the collection\n       ** Added pymongo 2.1\n    :param username: username to authenticate with\n    :param password: password to authenticate with\n    :param authentication_source: database to authenticate against\n    :param authentication_mechanism: database authentication mechanisms.\n        By default, use SCRAM-SHA-1 with MongoDB 3.0 and later,\n        MONGODB-CR (MongoDB Challenge Response protocol) for older servers.\n    :param is_mock: explicitly use mongomock for this connection\n        (can also be done by using `mongomock://` as db host prefix)\n    :param kwargs: allow ad-hoc parameters to be passed into the pymongo driver\n\n    .. versionchanged:: 0.10.6 - added mongomock support\n    \"\"\"\n    conn_settings = {\n        'name': name or 'test',\n        'host': host or 'localhost',\n        'port': port or 27017,\n        'read_preference': read_preference,\n        'username': username,\n        'password': password,\n        'authentication_source': authentication_source,\n        'authentication_mechanism': authentication_mechanism\n    }\n\n    conn_host = conn_settings['host']\n\n    # Host can be a list or a string, so if string, force to a list.\n    if isinstance(conn_host, six.string_types):\n        conn_host = [conn_host]\n\n    resolved_hosts = []\n    for entity in conn_host:\n\n        # Handle Mongomock\n        if entity.startswith('mongomock://'):\n            conn_settings['is_mock'] = True\n            # `mongomock://` is not a valid url prefix and must be replaced by `mongodb://`\n            resolved_hosts.append(entity.replace('mongomock://', 'mongodb://', 1))\n\n        # Handle URI style connections, only updating connection params which\n        # were explicitly specified in the URI.\n        elif '://' in entity:\n            uri_dict = uri_parser.parse_uri(entity)\n            resolved_hosts.append(entity)\n\n            if uri_dict.get('database'):\n                conn_settings['name'] = uri_dict.get('database')\n\n            for param in ('read_preference', 'username', 'password'):\n                if uri_dict.get(param):\n                    conn_settings[param] = uri_dict[param]\n\n            uri_options = uri_dict['options']\n            if 'replicaset' in uri_options:\n                conn_settings['replicaSet'] = uri_options['replicaset']\n            if 'authsource' in uri_options:\n                conn_settings['authentication_source'] = uri_options['authsource']\n            if 'authmechanism' in uri_options:\n                conn_settings['authentication_mechanism'] = uri_options['authmechanism']\n        else:\n            resolved_hosts.append(entity)\n    conn_settings['host'] = resolved_hosts\n\n    # Deprecated parameters that should not be passed on\n    kwargs.pop('slaves', None)\n    kwargs.pop('is_slave', None)\n\n    conn_settings.update(kwargs)\n    _connection_settings[alias] = conn_settings\n\n\ndef disconnect(alias=DEFAULT_CONNECTION_NAME):\n    \"\"\"Close the connection with a given alias.\"\"\"\n    if alias in _connections:\n        get_connection(alias=alias).close()\n        del _connections[alias]\n    if alias in _dbs:\n        del _dbs[alias]\n\n\ndef get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False):\n    \"\"\"Return a connection with a given alias.\"\"\"\n\n    # Connect to the database if not already connected\n    if reconnect:\n        disconnect(alias)\n\n    # If the requested alias already exists in the _connections list, return\n    # it immediately.\n    if alias in _connections:\n        return _connections[alias]\n\n    # Validate that the requested alias exists in the _connection_settings.\n    # Raise MongoEngineConnectionError if it doesn't.\n    if alias not in _connection_settings:\n        if alias == DEFAULT_CONNECTION_NAME:\n            msg = 'You have not defined a default connection'\n        else:\n            msg = 'Connection with alias \"%s\" has not been defined' % alias\n        raise MongoEngineConnectionError(msg)\n\n    def _clean_settings(settings_dict):\n        irrelevant_fields = set([\n            'name', 'username', 'password', 'authentication_source',\n            'authentication_mechanism'\n        ])\n        return {\n            k: v for k, v in settings_dict.items()\n            if k not in irrelevant_fields\n        }\n\n    # Retrieve a copy of the connection settings associated with the requested\n    # alias and remove the database name and authentication info (we don't\n    # care about them at this point).\n    conn_settings = _clean_settings(_connection_settings[alias].copy())\n\n    # Determine if we should use PyMongo's or mongomock's MongoClient.\n    is_mock = conn_settings.pop('is_mock', False)\n    if is_mock:\n        try:\n            import mongomock\n        except ImportError:\n            raise RuntimeError('You need mongomock installed to mock '\n                               'MongoEngine.')\n        connection_class = mongomock.MongoClient\n    else:\n        connection_class = MongoClient\n\n        # For replica set connections with PyMongo 2.x, use\n        # MongoReplicaSetClient.\n        # TODO remove this once we stop supporting PyMongo 2.x.\n        if 'replicaSet' in conn_settings and not IS_PYMONGO_3:\n            connection_class = MongoReplicaSetClient\n            conn_settings['hosts_or_uri'] = conn_settings.pop('host', None)\n\n            # hosts_or_uri has to be a string, so if 'host' was provided\n            # as a list, join its parts and separate them by ','\n            if isinstance(conn_settings['hosts_or_uri'], list):\n                conn_settings['hosts_or_uri'] = ','.join(\n                    conn_settings['hosts_or_uri'])\n\n            # Discard port since it can't be used on MongoReplicaSetClient\n            conn_settings.pop('port', None)\n\n    # Iterate over all of the connection settings and if a connection with\n    # the same parameters is already established, use it instead of creating\n    # a new one.\n    existing_connection = None\n    connection_settings_iterator = (\n        (db_alias, settings.copy())\n        for db_alias, settings in _connection_settings.items()\n    )\n    for db_alias, connection_settings in connection_settings_iterator:\n        connection_settings = _clean_settings(connection_settings)\n        if conn_settings == connection_settings and _connections.get(db_alias):\n            existing_connection = _connections[db_alias]\n            break\n\n    # If an existing connection was found, assign it to the new alias\n    if existing_connection:\n        _connections[alias] = existing_connection\n    else:\n        # Otherwise, create the new connection for this alias. Raise\n        # MongoEngineConnectionError if it can't be established.\n        try:\n            _connections[alias] = connection_class(**conn_settings)\n        except Exception as e:\n            raise MongoEngineConnectionError(\n                'Cannot connect to database %s :\\n%s' % (alias, e))\n\n    return _connections[alias]\n\n\ndef get_db(alias=DEFAULT_CONNECTION_NAME, reconnect=False):\n    if reconnect:\n        disconnect(alias)\n\n    if alias not in _dbs:\n        conn = get_connection(alias)\n        conn_settings = _connection_settings[alias]\n        db = conn[conn_settings['name']]\n        auth_kwargs = {'source': conn_settings['authentication_source']}\n        if conn_settings['authentication_mechanism'] is not None:\n            auth_kwargs['mechanism'] = conn_settings['authentication_mechanism']\n        # Authenticate if necessary\n        if conn_settings['username'] and (conn_settings['password'] or\n                                          conn_settings['authentication_mechanism'] == 'MONGODB-X509'):\n            db.authenticate(conn_settings['username'], conn_settings['password'], **auth_kwargs)\n        _dbs[alias] = db\n    return _dbs[alias]\n\n\ndef connect(db=None, alias=DEFAULT_CONNECTION_NAME, **kwargs):\n    \"\"\"Connect to the database specified by the 'db' argument.\n\n    Connection settings may be provided here as well if the database is not\n    running on the default port on localhost. If authentication is needed,\n    provide username and password arguments as well.\n\n    Multiple databases are supported by using aliases.  Provide a separate\n    `alias` to connect to a different instance of :program:`mongod`.\n\n    .. versionchanged:: 0.6 - added multiple database support.\n    \"\"\"\n    if alias not in _connections:\n        register_connection(alias, db, **kwargs)\n\n    return get_connection(alias)\n\n\n# Support old naming convention\n_get_connection = get_connection\n_get_db = get_db\n", "path": "mongoengine/connection.py"}], "after_files": [{"content": "from pymongo import MongoClient, ReadPreference, uri_parser\nimport six\n\nfrom mongoengine.python_support import IS_PYMONGO_3\n\n__all__ = ['MongoEngineConnectionError', 'connect', 'register_connection',\n           'DEFAULT_CONNECTION_NAME']\n\n\nDEFAULT_CONNECTION_NAME = 'default'\n\nif IS_PYMONGO_3:\n    READ_PREFERENCE = ReadPreference.PRIMARY\nelse:\n    from pymongo import MongoReplicaSetClient\n    READ_PREFERENCE = False\n\n\nclass MongoEngineConnectionError(Exception):\n    \"\"\"Error raised when the database connection can't be established or\n    when a connection with a requested alias can't be retrieved.\n    \"\"\"\n    pass\n\n\n_connection_settings = {}\n_connections = {}\n_dbs = {}\n\n\ndef register_connection(alias, name=None, host=None, port=None,\n                        read_preference=READ_PREFERENCE,\n                        username=None, password=None,\n                        authentication_source=None,\n                        authentication_mechanism=None,\n                        **kwargs):\n    \"\"\"Add a connection.\n\n    :param alias: the name that will be used to refer to this connection\n        throughout MongoEngine\n    :param name: the name of the specific database to use\n    :param host: the host name of the :program:`mongod` instance to connect to\n    :param port: the port that the :program:`mongod` instance is running on\n    :param read_preference: The read preference for the collection\n       ** Added pymongo 2.1\n    :param username: username to authenticate with\n    :param password: password to authenticate with\n    :param authentication_source: database to authenticate against\n    :param authentication_mechanism: database authentication mechanisms.\n        By default, use SCRAM-SHA-1 with MongoDB 3.0 and later,\n        MONGODB-CR (MongoDB Challenge Response protocol) for older servers.\n    :param is_mock: explicitly use mongomock for this connection\n        (can also be done by using `mongomock://` as db host prefix)\n    :param kwargs: ad-hoc parameters to be passed into the pymongo driver,\n        for example maxpoolsize, tz_aware, etc. See the documentation\n        for pymongo's `MongoClient` for a full list.\n\n    .. versionchanged:: 0.10.6 - added mongomock support\n    \"\"\"\n    conn_settings = {\n        'name': name or 'test',\n        'host': host or 'localhost',\n        'port': port or 27017,\n        'read_preference': read_preference,\n        'username': username,\n        'password': password,\n        'authentication_source': authentication_source,\n        'authentication_mechanism': authentication_mechanism\n    }\n\n    conn_host = conn_settings['host']\n\n    # Host can be a list or a string, so if string, force to a list.\n    if isinstance(conn_host, six.string_types):\n        conn_host = [conn_host]\n\n    resolved_hosts = []\n    for entity in conn_host:\n\n        # Handle Mongomock\n        if entity.startswith('mongomock://'):\n            conn_settings['is_mock'] = True\n            # `mongomock://` is not a valid url prefix and must be replaced by `mongodb://`\n            resolved_hosts.append(entity.replace('mongomock://', 'mongodb://', 1))\n\n        # Handle URI style connections, only updating connection params which\n        # were explicitly specified in the URI.\n        elif '://' in entity:\n            uri_dict = uri_parser.parse_uri(entity)\n            resolved_hosts.append(entity)\n\n            if uri_dict.get('database'):\n                conn_settings['name'] = uri_dict.get('database')\n\n            for param in ('read_preference', 'username', 'password'):\n                if uri_dict.get(param):\n                    conn_settings[param] = uri_dict[param]\n\n            uri_options = uri_dict['options']\n            if 'replicaset' in uri_options:\n                conn_settings['replicaSet'] = uri_options['replicaset']\n            if 'authsource' in uri_options:\n                conn_settings['authentication_source'] = uri_options['authsource']\n            if 'authmechanism' in uri_options:\n                conn_settings['authentication_mechanism'] = uri_options['authmechanism']\n        else:\n            resolved_hosts.append(entity)\n    conn_settings['host'] = resolved_hosts\n\n    # Deprecated parameters that should not be passed on\n    kwargs.pop('slaves', None)\n    kwargs.pop('is_slave', None)\n\n    conn_settings.update(kwargs)\n    _connection_settings[alias] = conn_settings\n\n\ndef disconnect(alias=DEFAULT_CONNECTION_NAME):\n    \"\"\"Close the connection with a given alias.\"\"\"\n    if alias in _connections:\n        get_connection(alias=alias).close()\n        del _connections[alias]\n    if alias in _dbs:\n        del _dbs[alias]\n\n\ndef get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False):\n    \"\"\"Return a connection with a given alias.\"\"\"\n\n    # Connect to the database if not already connected\n    if reconnect:\n        disconnect(alias)\n\n    # If the requested alias already exists in the _connections list, return\n    # it immediately.\n    if alias in _connections:\n        return _connections[alias]\n\n    # Validate that the requested alias exists in the _connection_settings.\n    # Raise MongoEngineConnectionError if it doesn't.\n    if alias not in _connection_settings:\n        if alias == DEFAULT_CONNECTION_NAME:\n            msg = 'You have not defined a default connection'\n        else:\n            msg = 'Connection with alias \"%s\" has not been defined' % alias\n        raise MongoEngineConnectionError(msg)\n\n    def _clean_settings(settings_dict):\n        irrelevant_fields = set([\n            'name', 'username', 'password', 'authentication_source',\n            'authentication_mechanism'\n        ])\n        return {\n            k: v for k, v in settings_dict.items()\n            if k not in irrelevant_fields\n        }\n\n    # Retrieve a copy of the connection settings associated with the requested\n    # alias and remove the database name and authentication info (we don't\n    # care about them at this point).\n    conn_settings = _clean_settings(_connection_settings[alias].copy())\n\n    # Determine if we should use PyMongo's or mongomock's MongoClient.\n    is_mock = conn_settings.pop('is_mock', False)\n    if is_mock:\n        try:\n            import mongomock\n        except ImportError:\n            raise RuntimeError('You need mongomock installed to mock '\n                               'MongoEngine.')\n        connection_class = mongomock.MongoClient\n    else:\n        connection_class = MongoClient\n\n        # For replica set connections with PyMongo 2.x, use\n        # MongoReplicaSetClient.\n        # TODO remove this once we stop supporting PyMongo 2.x.\n        if 'replicaSet' in conn_settings and not IS_PYMONGO_3:\n            connection_class = MongoReplicaSetClient\n            conn_settings['hosts_or_uri'] = conn_settings.pop('host', None)\n\n            # hosts_or_uri has to be a string, so if 'host' was provided\n            # as a list, join its parts and separate them by ','\n            if isinstance(conn_settings['hosts_or_uri'], list):\n                conn_settings['hosts_or_uri'] = ','.join(\n                    conn_settings['hosts_or_uri'])\n\n            # Discard port since it can't be used on MongoReplicaSetClient\n            conn_settings.pop('port', None)\n\n    # Iterate over all of the connection settings and if a connection with\n    # the same parameters is already established, use it instead of creating\n    # a new one.\n    existing_connection = None\n    connection_settings_iterator = (\n        (db_alias, settings.copy())\n        for db_alias, settings in _connection_settings.items()\n    )\n    for db_alias, connection_settings in connection_settings_iterator:\n        connection_settings = _clean_settings(connection_settings)\n        if conn_settings == connection_settings and _connections.get(db_alias):\n            existing_connection = _connections[db_alias]\n            break\n\n    # If an existing connection was found, assign it to the new alias\n    if existing_connection:\n        _connections[alias] = existing_connection\n    else:\n        # Otherwise, create the new connection for this alias. Raise\n        # MongoEngineConnectionError if it can't be established.\n        try:\n            _connections[alias] = connection_class(**conn_settings)\n        except Exception as e:\n            raise MongoEngineConnectionError(\n                'Cannot connect to database %s :\\n%s' % (alias, e))\n\n    return _connections[alias]\n\n\ndef get_db(alias=DEFAULT_CONNECTION_NAME, reconnect=False):\n    if reconnect:\n        disconnect(alias)\n\n    if alias not in _dbs:\n        conn = get_connection(alias)\n        conn_settings = _connection_settings[alias]\n        db = conn[conn_settings['name']]\n        auth_kwargs = {'source': conn_settings['authentication_source']}\n        if conn_settings['authentication_mechanism'] is not None:\n            auth_kwargs['mechanism'] = conn_settings['authentication_mechanism']\n        # Authenticate if necessary\n        if conn_settings['username'] and (conn_settings['password'] or\n                                          conn_settings['authentication_mechanism'] == 'MONGODB-X509'):\n            db.authenticate(conn_settings['username'], conn_settings['password'], **auth_kwargs)\n        _dbs[alias] = db\n    return _dbs[alias]\n\n\ndef connect(db=None, alias=DEFAULT_CONNECTION_NAME, **kwargs):\n    \"\"\"Connect to the database specified by the 'db' argument.\n\n    Connection settings may be provided here as well if the database is not\n    running on the default port on localhost. If authentication is needed,\n    provide username and password arguments as well.\n\n    Multiple databases are supported by using aliases. Provide a separate\n    `alias` to connect to a different instance of :program:`mongod`.\n\n    See the docstring for `register_connection` for more details about all\n    supported kwargs.\n\n    .. versionchanged:: 0.6 - added multiple database support.\n    \"\"\"\n    if alias not in _connections:\n        register_connection(alias, db, **kwargs)\n\n    return get_connection(alias)\n\n\n# Support old naming convention\n_get_connection = get_connection\n_get_db = get_db\n", "path": "mongoengine/connection.py"}]}