Skip to content

URL Tools

URL parsing, escaping, and scheme resolution helpers conforming to WHATWG URL and RFC standards.

proxy_string.url_tools

URL parsing, escaping, and scheme resolution helpers.

build_url

build_url(
    scheme: str,
    host: str,
    port: int,
    username: str | None = None,
    password: str | None = None,
) -> str

Constructs a standard URL string from individual proxy components.

Parameters:

Name Type Description Default
scheme str

The URL scheme/protocol (e.g. 'http', 'socks5h').

required
host str

Hostname or IP address (IPv6 will be bracketed if needed).

required
port int

Connection port number.

required
username str | None

Optional username credential.

None
password str | None

Optional password credential.

None

Returns:

Name Type Description
str str

Formatted URL string.

Source code in src/proxy_string/url_tools.py
def build_url(
    scheme: str,
    host: str,
    port: int,
    username: str | None = None,
    password: str | None = None,
) -> str:
    """Constructs a standard URL string from individual proxy components.

    Args:
        scheme: The URL scheme/protocol (e.g. 'http', 'socks5h').
        host: Hostname or IP address (IPv6 will be bracketed if needed).
        port: Connection port number.
        username: Optional username credential.
        password: Optional password credential.

    Returns:
        str: Formatted URL string.
    """
    if username is not None and password is not None:
        target_user_passw = f"{quote_all(username)}:{quote_all(password)}@"
    elif username is not None:
        target_user_passw = f"{quote_all(username)}@"
    elif password is not None:
        target_user_passw = f":{quote_all(password)}@"
    else:
        target_user_passw = ""

    if ":" in host and not host.startswith("["):
        host = f"[{host}]"

    return f"{scheme}://{target_user_passw}{host}:{port}"

get_protocol

get_protocol(
    scheme: str,
) -> tuple[ProxyServerProtocol, bool | None]

Resolves a scheme name into a ProxyServerProtocol and remote_dns flag.

Parameters:

Name Type Description Default
scheme str

URL scheme string (e.g. 'socks5h', 'http').

required

Returns:

Type Description
tuple[ProxyServerProtocol, bool | None]

tuple[ProxyServerProtocol, bool | None]: Tuple of protocol enum and remote_dns setting.

Raises:

Type Description
ValueError

If scheme is not a recognized proxy protocol.

Source code in src/proxy_string/url_tools.py
def get_protocol(scheme: str) -> tuple[ProxyServerProtocol, bool | None]:
    """Resolves a scheme name into a ProxyServerProtocol and remote_dns flag.

    Args:
        scheme: URL scheme string (e.g. 'socks5h', 'http').

    Returns:
        tuple[ProxyServerProtocol, bool | None]: Tuple of protocol enum and
            remote_dns setting.

    Raises:
        ValueError: If scheme is not a recognized proxy protocol.
    """
    scheme = scheme.lower()
    if scheme in ("socks5h", "socks4a"):
        remote_dns = True
    elif scheme in ("socks5", "socks4"):
        remote_dns = None
    else:
        remote_dns = False
    protocol = ProxyServerProtocol(
        {"socks5h": "socks5", "socks4a": "socks4"}.get(scheme, scheme)
    )
    return protocol, remote_dns

get_scheme

get_scheme(
    protocol: ProxyServerProtocol | str,
    remote_dns: bool | None,
    socks_ext: bool = True,
) -> str

Determines the appropriate URL scheme based on protocol and DNS resolution mode.

Parameters:

Name Type Description Default
protocol ProxyServerProtocol | str

Proxy protocol enum member or protocol name string.

required
remote_dns bool | None

Whether remote DNS resolution is enabled.

required
socks_ext bool

Whether to use extended SOCKS schemes ('socks4a', 'socks5h').

True

Returns:

Name Type Description
str str

Resolved scheme string.

Source code in src/proxy_string/url_tools.py
def get_scheme(
    protocol: ProxyServerProtocol | str,
    remote_dns: bool | None,
    socks_ext: bool = True,
) -> str:
    """Determines the appropriate URL scheme based on protocol and DNS resolution mode.

    Args:
        protocol: Proxy protocol enum member or protocol name string.
        remote_dns: Whether remote DNS resolution is enabled.
        socks_ext: Whether to use extended SOCKS schemes ('socks4a', 'socks5h').

    Returns:
        str: Resolved scheme string.
    """
    protocol = protocol.lower()
    if remote_dns and socks_ext:
        if protocol == ProxyServerProtocol.SOCKS4:
            return "socks4a"
        if protocol == ProxyServerProtocol.SOCKS5:
            return "socks5h"
    return protocol

quote_all

quote_all(
    input_string: str,
    encoding: str = "utf-8",
    errors: str = "strict",
) -> str

Percent-encodes all reserved characters in a string.

Encodes every character that is not alphanumeric, without treating any characters as safe.

Parameters:

Name Type Description Default
input_string str

The string to percent-encode.

required
encoding str

The text encoding to use (defaults to 'utf-8').

'utf-8'
errors str

Error handling scheme for decoding errors.

'strict'

Returns:

Name Type Description
str str

The fully percent-encoded string.

Source code in src/proxy_string/url_tools.py
def quote_all(
    input_string: str, encoding: str = "utf-8", errors: str = "strict"
) -> str:
    """Percent-encodes all reserved characters in a string.

    Encodes every character that is not alphanumeric, without treating
    any characters as safe.

    Args:
        input_string: The string to percent-encode.
        encoding: The text encoding to use (defaults to 'utf-8').
        errors: Error handling scheme for decoding errors.

    Returns:
        str: The fully percent-encoded string.
    """
    return quote(input_string, safe="", encoding=encoding, errors=errors)

unquote_all

unquote_all(
    input_string: str,
    encoding: str = "utf-8",
    errors: str = "strict",
) -> str

Decodes percent-encoded characters in a string.

Parameters:

Name Type Description Default
input_string str

The percent-encoded string.

required
encoding str

The text encoding to use (defaults to 'utf-8').

'utf-8'
errors str

Error handling scheme for decoding errors.

'strict'

Returns:

Name Type Description
str str

The decoded string.

Source code in src/proxy_string/url_tools.py
def unquote_all(
    input_string: str, encoding: str = "utf-8", errors: str = "strict"
) -> str:
    """Decodes percent-encoded characters in a string.

    Args:
        input_string: The percent-encoded string.
        encoding: The text encoding to use (defaults to 'utf-8').
        errors: Error handling scheme for decoding errors.

    Returns:
        str: The decoded string.
    """
    return unquote(input_string, encoding=encoding, errors=errors)

proxy_string.whatwg_url

WHATWG URL standard backend integration and IDNA decoding.

clear_cache

clear_cache() -> None

Clears internal WHATWG URL and IDNA parser caches.

Source code in src/proxy_string/whatwg_url.py
def clear_cache() -> None:
    """Clears internal WHATWG URL and IDNA parser caches."""
    _parse_url_cached.cache_clear()
    decode_idna.cache_clear()

decode_idna cached

decode_idna(encoded_domain: str) -> str

Decodes a punycode/IDNA domain to Unicode.

Parameters:

Name Type Description Default
encoded_domain str

Punycode-encoded domain name.

required

Returns:

Name Type Description
str str

Unicode representation of the domain name.

Source code in src/proxy_string/whatwg_url.py
@lru_cache
def decode_idna(encoded_domain: str) -> str:
    """Decodes a punycode/IDNA domain to Unicode.

    Args:
        encoded_domain: Punycode-encoded domain name.

    Returns:
        str: Unicode representation of the domain name.
    """
    decode = globals()[f"{CURRENT_BACKEND}_decode"]
    return decode(encoded_domain)

parse_url

parse_url(url: str) -> dict[str, Any]

Parses a proxy URL into a dictionary of proxy attributes.

Parameters:

Name Type Description Default
url str

Absolute proxy URL string.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Parsed proxy attributes.

Raises:

Type Description
InvalidProxyURLError

If URL has no scheme, missing host, or SOCKS4 is used with IPv6.

Source code in src/proxy_string/whatwg_url.py
def parse_url(url: str) -> dict[str, Any]:
    """Parses a proxy URL into a dictionary of proxy attributes.

    Args:
        url: Absolute proxy URL string.

    Returns:
        dict[str, Any]: Parsed proxy attributes.

    Raises:
        InvalidProxyURLError: If URL has no scheme, missing host, or SOCKS4 is
            used with IPv6.
    """
    return _parse_url_cached(url).copy()