Created
September 7, 2024 11:38
-
-
Save fastfingertips/e9e80d6e454e4d247633230429c514b1 to your computer and use it in GitHub Desktop.
helper functions for flask url redirects
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
from flask import request, url_for, redirect | |
from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl | |
def get_referer_or_default(default='main.index'): | |
"""Returns the Referer URL if available, otherwise the default URL.""" | |
return request.headers.get("Referer") or url_for(default) | |
def redirect_to_referer_or_default(default='main.index'): | |
"""Redirects to the Referer URL if available, otherwise to the default URL.""" | |
return redirect(request.headers.get("Referer") or url_for(default)) | |
def get_full_url(route, **kwargs): | |
"""Returns the full URL for a given route and additional query parameters.""" | |
return url_for(route, _external=True, **kwargs) | |
def get_query_param(param, default=None): | |
"""Returns the value of a query parameter from the request URL, or a default value.""" | |
return request.args.get(param, default) | |
def append_query_params(url, **kwargs): | |
"""Appends query parameters to an existing URL.""" | |
url_parts = list(urlparse(url)) | |
query = dict(parse_qsl(url_parts[4])) | |
query.update(kwargs) | |
url_parts[4] = urlencode(query) | |
return urlunparse(url_parts) | |
def get_previous_url(default='main.index'): | |
"""Returns the previous URL or the default route.""" | |
return request.referrer or url_for(default) | |
def redirect_to_default(default='main.index'): | |
"""Redirects to the default route.""" | |
return redirect(url_for(default)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment