absolute_url util (closes #9)

netiawifi
selfisekai 2020-09-18 18:12:30 +02:00
parent ba4cbf6590
commit 76eb3d22dc
2 changed files with 37 additions and 1 deletions

View File

@ -1,7 +1,7 @@
# flake8: noqa: E501
import re
from urllib.parse import parse_qs, quote as qs_quote
from urllib.parse import parse_qs, quote as qs_quote, urlparse
from datetime import datetime
import random
@ -131,3 +131,24 @@ def dump_qs(obj):
strng += qs_quote(str(el[0]), encoding="utf8") + "=" + \
qs_quote(str(el[1]), encoding="utf8") + "&"
return strng[:-1]
def absolute_url(new_url: str, old_url: str):
if new_url.startswith("http:") or new_url.startswith("https:"):
return new_url
old = urlparse(old_url)
scheme = old.scheme if old.scheme is not None else "http"
if new_url.startswith("://"):
return scheme + new_url
if new_url.startswith("//"):
return scheme + ":" + new_url
hostname = old.netloc
if new_url.startswith("/"):
return scheme + "://" + hostname + new_url
# like "hostname/path?query", if other checks fail
return scheme + "://" + new_url

15
tests/url_utils.py Normal file
View File

@ -0,0 +1,15 @@
from librefi.utils import absolute_url
OLD_URL = "https://sakamoto.pl/ddd"
NEW_URL_RELATIVE = "/DDD?test=yes"
# expected value
NEW_URL_ABSOLUTE = "https://sakamoto.pl/DDD?test=yes"
def test_basic():
abso = absolute_url(NEW_URL_RELATIVE, OLD_URL)
assert isinstance(abso, (str))
print(abso)
assert abso == NEW_URL_ABSOLUTE
pass