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 09a93f6
Showing 1 changed file with 29 additions and 6 deletions.
35 changes: 29 additions & 6 deletions optimade/server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,7 @@ def parse_config_file(self) -> dict[str, Any]:
encoding = self.config.get("env_file_encoding")

config_file_env = os.getenv("OPTIMADE_CONFIG_FILE")
if config_file_env is None:
config_file = Path(config_file_env or DEFAULT_CONFIG_FILE_PATH)
config_file = Path(config_file_env or DEFAULT_CONFIG_FILE_PATH)

parsed_config_file = {}
if config_file.is_file():
Expand Down Expand Up @@ -223,11 +222,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 +483,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 09a93f6

Please sign in to comment.