Skip to content

Commit 2484ae4

Browse files
committed
[wip] parse db name out of connection string
1 parent ac62bcb commit 2484ae4

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

django_mongodb_backend/base.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from pymongo.collection import Collection
1212
from pymongo.driver_info import DriverInfo
1313
from pymongo.mongo_client import MongoClient
14+
from pymongo.uri_parser import parse_uri
1415

1516
from . import __version__ as django_mongodb_backend_version
1617
from . import dbapi as Database
@@ -157,6 +158,14 @@ def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS):
157158
self.in_atomic_block_mongo = False
158159
# Current number of nested 'atomic' calls.
159160
self.nested_atomics = 0
161+
if self.settings_dict["NAME"] == "":
162+
host = self.settings_dict["HOST"]
163+
if host.startswith(("mongodb://", "mongodb+srv://")):
164+
uri = parse_uri(host)
165+
if database := uri.get("database"):
166+
self.settings_dict["NAME"] = database
167+
else:
168+
raise ImproperlyConfigured('settings.DATABASES is missing the "NAME" value.')
160169

161170
def get_collection(self, name, **kwargs):
162171
collection = Collection(self.database, name, **kwargs)
@@ -183,8 +192,6 @@ def init_connection_state(self):
183192

184193
def get_connection_params(self):
185194
settings_dict = self.settings_dict
186-
if not settings_dict["NAME"]:
187-
raise ImproperlyConfigured('settings.DATABASES is missing the "NAME" value.')
188195
params = {
189196
"host": settings_dict["HOST"] or None,
190197
**settings_dict["OPTIONS"],

tests/backend_/test_base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def test_database_name_empty(self):
1212
settings["NAME"] = ""
1313
msg = 'settings.DATABASES is missing the "NAME" value.'
1414
with self.assertRaisesMessage(ImproperlyConfigured, msg):
15-
DatabaseWrapper(settings).get_connection_params()
15+
DatabaseWrapper(settings)
1616

1717
def test_host(self):
1818
settings = connection.settings_dict.copy()

0 commit comments

Comments
 (0)