2018-11-14 18:14:14 +00:00
|
|
|
"""URL-related utils"""
|
|
|
|
from urllib.parse import urlparse
|
|
|
|
|
2020-05-08 15:10:27 +01:00
|
|
|
from django.http import HttpResponse
|
|
|
|
from django.shortcuts import redirect, reverse
|
2020-05-11 14:01:14 +01:00
|
|
|
from django.urls import NoReverseMatch
|
2020-05-08 15:10:27 +01:00
|
|
|
from django.utils.http import urlencode
|
2020-05-11 14:01:14 +01:00
|
|
|
from structlog import get_logger
|
|
|
|
|
|
|
|
LOGGER = get_logger()
|
2020-05-08 15:10:27 +01:00
|
|
|
|
2018-11-14 18:14:14 +00:00
|
|
|
|
|
|
|
def is_url_absolute(url):
|
|
|
|
"""Check if domain is absolute to prevent user from being redirect somewhere else"""
|
|
|
|
return bool(urlparse(url).netloc)
|
2020-05-08 15:10:27 +01:00
|
|
|
|
|
|
|
|
|
|
|
def redirect_with_qs(view: str, get_query_set=None, **kwargs) -> HttpResponse:
|
|
|
|
"""Wrapper to redirect whilst keeping GET Parameters"""
|
2020-05-11 14:01:14 +01:00
|
|
|
try:
|
|
|
|
target = reverse(view, kwargs=kwargs)
|
|
|
|
except NoReverseMatch:
|
2020-05-11 20:58:02 +01:00
|
|
|
if not is_url_absolute(view):
|
|
|
|
return redirect(view)
|
2020-05-11 14:01:14 +01:00
|
|
|
LOGGER.debug("redirect target is not a valid view", view=view)
|
|
|
|
raise
|
|
|
|
else:
|
|
|
|
if get_query_set:
|
|
|
|
target += "?" + urlencode(get_query_set.items())
|
|
|
|
return redirect(target)
|