Skip to content

Instantly share code, notes, and snippets.

@premchalmeti
Created January 17, 2023 07:01
Show Gist options
  • Save premchalmeti/464cb92e26a540eadecf3122e0ae44df to your computer and use it in GitHub Desktop.
Save premchalmeti/464cb92e26a540eadecf3122e0ae44df to your computer and use it in GitHub Desktop.
Safe version of urljoin, joins the URIs carefully considering the prefixes and trailing slashes.
def safe_urljoin(*uris) -> str:
"""
Joins the URIs carefully considering the prefixes and trailing slashes.
The trailing slash for the end URI is handled separately.
>>> safe_urljoin("https://px.com/", "adunits/", "/both/", "/left")
>>> 'https://px.com/adunits/both/left'
>>> safe_urljoin("https://px.com/", "adunits/", "/both/", "right/")
>>> 'https://px.com/adunits/both/right/'
>>> safe_urljoin("https://px.com/", "adunits/", "/both/", "right/", "none")
>>> 'https://px.com/adunits/both/right/none'
>>> safe_urljoin("https://px.com/", "adunits/", "/both/", "right/", "none/")
>>> 'https://px.com/adunits/both/right/none/'
"""
if len(uris) == 1:
return uris[0]
safe_urls = [
f"{url.lstrip('/')}/" if not url.endswith("/") else url.lstrip("/")
for url in uris[:-1]
]
safe_urls.append(uris[-1].lstrip("/"))
return "".join(safe_urls)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment