Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions optimade/server/routers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,16 +232,19 @@ def get_base_url(

Take the base URL from the config file, if it exists, otherwise use the request.
"""
if CONFIG.base_url:
return CONFIG.base_url.rstrip("/")

parsed_url_request = (
urllib.parse.urlparse(parsed_url_request)
if isinstance(parsed_url_request, str)
else parsed_url_request
)
return (
CONFIG.base_url.rstrip("/")
if CONFIG.base_url
else f"{parsed_url_request.scheme}://{parsed_url_request.netloc}"
)
base_url = f"{parsed_url_request.scheme}://{parsed_url_request.netloc}"
if CONFIG.root_path:
base_url = base_url + CONFIG.root_path.rstrip("/")

return base_url


def get_entries(
Expand Down
35 changes: 35 additions & 0 deletions tests/server/routers/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,38 @@ def test_get_providers_warning(caplog, top_dir):
from optimade.server.data import providers

assert providers == providers_cache


def test_get_base_url():
"""
This tests whether the base_url is correctly extracted from the request.
"""
from optimade.server.config import CONFIG
from optimade.server.routers.utils import get_base_url

base_url_org = CONFIG.base_url
root_path_org = CONFIG.root_path
CONFIG.base_url = None
CONFIG.root_path = "/optimade"
request_urls = (
"http://www.example.com",
"http://www.example.com/",
"http://www.example.com/optimade/v1/links",
"http://www.structures.com/links",
"https://www.links.org/optimade/structures/123456",
)
base_urls = (
"http://www.example.com/optimade",
"http://www.example.com/optimade",
"http://www.example.com/optimade",
"http://www.structures.com/optimade",
"https://www.links.org/optimade",
)
results = []
for request_url in request_urls:
results.append(get_base_url(request_url))

CONFIG.base_url = base_url_org
CONFIG.root_path = root_path_org
for i in range(len(base_urls)):
assert results[i] == base_urls[i]