Skip to content

Parsers

Parsing helpers and format auto-detection functions for string-formatted proxies.

proxy_string.parsers

Parsers and regex patterns for text-formatted proxy strings.

detect_possible_formats

detect_possible_formats(
    proxy_string: str,
) -> tuple[tuple[ProxyStringFormat, dict[str, Any]], ...]

Detects viable proxy string formats and attempts to parse the string.

Note

When credentials (usernames or passwords) contain only digits and fall into a valid port range (0..65535), 4-part colon-delimited strings can be ambiguous. Explicitly passing ProxyStringFormat is recommended in such cases.

Parameters:

Name Type Description Default
proxy_string str

Raw proxy string without scheme.

required

Returns:

Type Description
tuple[tuple[ProxyStringFormat, dict[str, Any]], ...]

tuple[tuple[ProxyStringFormat, dict[str, Any]], ...]: Parsed formats and data dictionaries.

Source code in src/proxy_string/parsers.py
def detect_possible_formats(
    proxy_string: str,
) -> tuple[tuple[ProxyStringFormat, dict[str, Any]], ...]:
    """Detects viable proxy string formats and attempts to parse the string.

    Note:
        When credentials (usernames or passwords) contain only digits and fall into
        a valid port range (0..65535), 4-part colon-delimited strings can be ambiguous.
        Explicitly passing `ProxyStringFormat` is recommended in such cases.

    Args:
        proxy_string: Raw proxy string without scheme.

    Returns:
        tuple[tuple[ProxyStringFormat, dict[str, Any]], ...]: Parsed formats
            and data dictionaries.
    """
    proxy_string = proxy_string.strip()

    # (1) check if proxy string is an URL
    if "://" in proxy_string:
        with suppress(ProxyStringError, ValueError):
            return (
                (
                    ProxyStringFormat.URL,
                    parse_proxy_string(proxy_string, ProxyStringFormat.URL),
                ),
            )
        return ()

    matches: list[tuple[ProxyStringFormat, dict[str, Any]]] = []

    # (2) check if proxy string contains "@" ("u:p@h:p" or "h:p@u:p")
    if "@" in proxy_string:
        possible_formats = (
            ProxyStringFormat.USER_PASS_AT_HOST_PORT,
            ProxyStringFormat.HOST_PORT_AT_USER_PASS,
        )
        for fmt in possible_formats:
            with suppress(ProxyStringError, ValueError):
                matches.append((fmt, parse_proxy_string(proxy_string, fmt)))
        return tuple(matches)

    # (3) check if proxy string is just host + port (hostname and IPv4 only)
    if proxy_string.count(":") == 1:
        with suppress(ProxyStringError, ValueError):
            return (
                (
                    ProxyStringFormat.HOST_PORT,
                    parse_proxy_string(proxy_string, ProxyStringFormat.HOST_PORT),
                ),
            )
        return ()

    # (4) check for the rest formats
    possible_formats = (
        ProxyStringFormat.HOST_PORT,  # actually, for IPv6 only
        ProxyStringFormat.HOST_PORT_USER_PASS,
        ProxyStringFormat.USER_PASS_HOST_PORT,
    )
    for fmt in possible_formats:
        with suppress(ProxyStringError, ValueError):
            matches.append((fmt, parse_proxy_string(proxy_string, fmt)))
    return tuple(matches)

parse_proxy_string

parse_proxy_string(
    proxy_string: str, proxy_format: ProxyStringFormat
) -> dict[str, Any]

Parses a proxy string according to the specified format.

Parameters:

Name Type Description Default
proxy_string str

Proxy string to parse.

required
proxy_format ProxyStringFormat

Expected ProxyStringFormat.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Extracted proxy parameters (host, port, username, password).

Raises:

Type Description
InvalidProxyStringError

If the string does not match the expected format.

Source code in src/proxy_string/parsers.py
def parse_proxy_string(
    proxy_string: str,
    proxy_format: ProxyStringFormat,
) -> dict[str, Any]:
    """Parses a proxy string according to the specified format.

    Args:
        proxy_string: Proxy string to parse.
        proxy_format: Expected ProxyStringFormat.

    Returns:
        dict[str, Any]: Extracted proxy parameters (host, port, username, password).

    Raises:
        InvalidProxyStringError: If the string does not match the expected format.
    """
    proxy_string = proxy_string.strip()
    if proxy_format == ProxyStringFormat.URL:
        return parse_url(proxy_string)

    match = PROXY_FORMAT_REGEXPS[proxy_format].match(proxy_string)
    if match is not None:
        groups = match.groupdict()
        username = groups.get("username")
        password = groups.get("password")
        if username == "" and password == "":
            username = None
            password = None
        return {
            "host": groups["host"],
            "port": int(groups["port"]),
            "username": username or None,
            "password": password,
        }

    raise InvalidProxyStringError(
        "Unable to parse the proxy string: invalid format.", proxy_string=proxy_string
    )