Skip to content

Commit

Permalink
Prefer mongo_database value from mongo_uri if set in config
Browse files Browse the repository at this point in the history
  • Loading branch information
ml-evs committed Nov 17, 2024
1 parent a27687b commit 365120a
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions optimade/server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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,
Expand Down

0 comments on commit 365120a

Please sign in to comment.