diff options
author | Andrew Godwin | 2022-12-12 07:22:11 -0700 |
---|---|---|
committer | Andrew Godwin | 2022-12-12 11:56:49 -0700 |
commit | 8ffe4bc1453660c1f211496074ebcc68c924327e (patch) | |
tree | 7503fdcd6aafd32e9ec75dc7190699e004cf2935 /core | |
parent | 35a45f1c55fba69d690929c9420df565e7c5efcc (diff) | |
download | takahe-8ffe4bc1453660c1f211496074ebcc68c924327e.tar.gz takahe-8ffe4bc1453660c1f211496074ebcc68c924327e.tar.bz2 takahe-8ffe4bc1453660c1f211496074ebcc68c924327e.zip |
A better way of handling URIs between local/remote
Diffstat (limited to 'core')
-rw-r--r-- | core/uris.py | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/core/uris.py b/core/uris.py new file mode 100644 index 0000000..9ed2a32 --- /dev/null +++ b/core/uris.py @@ -0,0 +1,34 @@ +from urllib.parse import urljoin + +from django.conf import settings + + +class RelativeAbsoluteUrl: + """ + Represents a URL that can have both "relative" and "absolute" forms + for various use either locally or remotely. + """ + + absolute: str + relative: str + + def __init__(self, absolute: str, relative: str | None = None): + if "://" not in absolute: + raise ValueError(f"Absolute URL {absolute!r} is not absolute!") + self.absolute = absolute + self.relative = relative or absolute + + +class AutoAbsoluteUrl(RelativeAbsoluteUrl): + """ + Automatically makes the absolute variant by using either settings.MAIN_DOMAIN + or a passed identity's URI domain. + """ + + def __init__(self, relative: str, identity=None): + self.relative = relative + if identity: + absolute_prefix = f"https://{identity.domain.uri_domain}/" + else: + absolute_prefix = f"https://{settings.MAIN_DOMAIN}/" + self.absolute = urljoin(absolute_prefix, self.relative) |