Skip to content

meringue.core.utils.urls ¤

add_params_to_url ¤

add_params_to_url(url: str, params: dict | str) -> str

Add GET parameters to the URL.

Existing parameters and the fragment are kept; new parameters are appended to the end of the query string (even if a parameter with the same name already exists).

Attributes:

  • url –

    Source URL.

  • params –

    Parameters to add, as a dict or an already encoded query string.

Examples:

>>> add_params_to_url("https://example.com/?baz=qux#anchor", {"foo": "bar"})
'https://example.com/?baz=qux&foo=bar#anchor'

Returns:

  • str –

    URL with parameters.

Source code in meringue/core/utils/urls.py
def add_params_to_url(url: str, params: dict | str) -> str:
    """
    Add GET parameters to the URL.

    Existing parameters and the fragment are kept; new parameters are appended
    to the end of the query string (even if a parameter with the same name already exists).

    Attributes:
        url: Source URL.
        params: Parameters to add, as a dict or an already encoded query string.

    Examples:
        ```pycon
        >>> add_params_to_url("https://example.com/?baz=qux#anchor", {"foo": "bar"})
        'https://example.com/?baz=qux&foo=bar#anchor'
        ```

    Returns:
        URL with parameters.
    """

    if not params:
        return url

    if not isinstance(params, str):
        params = parse.urlencode(params)

    parsed_url = parse.urlparse(url)
    if parsed_url.query:
        parsed_url = parsed_url._replace(query=f"{parsed_url.query}&{params}")
    else:
        parsed_url = parsed_url._replace(query=params)

    return parsed_url.geturl()