diff --git a/optimade/server/config.py b/optimade/server/config.py index ffc61dd94..6d0b9d003 100644 --- a/optimade/server/config.py +++ b/optimade/server/config.py @@ -273,6 +273,17 @@ def set_implementation_version(cls, v): res.update(v) return res + @validator("root_path", pre=False) + def remove_end_slashes(cls, value: str) -> str: + """Remove ending slashes from root_path""" + if isinstance(value, str): + while value.endswith("/"): + value = value[:-1] + while value.startswith("/"): + value = value[1:] + value = f"/{value}" + return value + @root_validator(pre=True) def use_real_mongo_override(cls, values): """Overrides the `database_backend` setting with MongoDB and diff --git a/optimade/server/routers/utils.py b/optimade/server/routers/utils.py index 45ecdefcd..e1c12a5e2 100644 --- a/optimade/server/routers/utils.py +++ b/optimade/server/routers/utils.py @@ -185,10 +185,11 @@ def get_base_url( if isinstance(parsed_url_request, str) else parsed_url_request ) + root_path = CONFIG.root_path.rstrip("/") if CONFIG.root_path else "" return ( CONFIG.base_url.rstrip("/") if CONFIG.base_url - else f"{parsed_url_request.scheme}://{parsed_url_request.netloc}" + else f"{parsed_url_request.scheme}://{parsed_url_request.netloc}{root_path}" ) @@ -213,9 +214,10 @@ def get_entries( query = urllib.parse.parse_qs(request.url.query) query["page_offset"] = int(query.get("page_offset", [0])[0]) + len(results) urlencoded = urllib.parse.urlencode(query, doseq=True) - base_url = get_base_url(request.url) + root_path = CONFIG.root_path.rstrip("/") if CONFIG.root_path else "" + url = f"{get_base_url(request.url)}{request.url.path.replace(root_path, '')}" - links = ToplevelLinks(next=f"{base_url}{request.url.path}?{urlencoded}") + links = ToplevelLinks(next=f"{url}?{urlencoded}") else: links = ToplevelLinks(next=None) diff --git a/tests/test_config.json b/tests/test_config.json index 683fd248d..7bc725eca 100644 --- a/tests/test_config.json +++ b/tests/test_config.json @@ -2,6 +2,7 @@ "debug": false, "default_db": "test_server", "base_url": "http://example.org", + "root_path": "custom_root_path/", "implementation": { "name": "Example implementation", "source_url": "https://github.com/Materials-Consortia/optimade-python-tools",