Created
January 17, 2023 07:01
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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