From 365120a1ed4b9468766a6a1a3955baedc2d57619 Mon Sep 17 00:00:00 2001 From: Matthew Evans Date: Sun, 17 Nov 2024 14:15:10 +0000 Subject: [PATCH] Prefer `mongo_database` value from `mongo_uri` if set in config --- optimade/server/config.py | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/optimade/server/config.py b/optimade/server/config.py index bdf108628..519ca8c72 100644 --- a/optimade/server/config.py +++ b/optimade/server/config.py @@ -223,11 +223,19 @@ class ServerConfig(BaseSettings): ] = 5 mongo_database: Annotated[ - str, Field(description="Mongo database for collection data") + str, + Field( + description="MongoDB database name to use; will be overwritten if also present in `mongo_uri`" + ), ] = "optimade" - mongo_uri: Annotated[str, Field(description="URI for the Mongo server")] = ( - "localhost:27017" - ) + mongo_uri: Annotated[ + str, + Field( + description="URI for the MongoDB instance", + examples=["mongodb://localhost:27017/optimade", "localhost:1000"], + ), + ] = "localhost:27017" + links_collection: Annotated[ str, Field(description="Mongo collection name for /links endpoint resources") ] = "links" @@ -476,6 +484,22 @@ def use_real_mongo_override(self) -> "ServerConfig": return self + @model_validator(mode="after") + def align_mongo_uri_and_mongo_database(self) -> "ServerConfig": + """Prefer the value of database name if set from `mongo_uri` rather than + `mongo_database`. + + """ + if self.database_backend == SupportedBackend.MONGODB: + if self.mongo_uri and self.mongo_database: + import pymongo.uri_parser + + uri: dict[str, Any] = pymongo.uri_parser.parse_uri(self.mongo_uri) + if uri.get("database"): + self.mongo_database = uri["database"] + + return self + @classmethod def settings_customise_sources( cls,