def _dns_quote(name):
    """Escape a name for use in a dns label

    this is _NOT_ fully domain-safe, but works often enough for realistic usernames.
    Fully safe would be full IDNA encoding,
    PLUS escaping non-IDNA-legal ascii,
    PLUS some encoding of boundary conditions
    """
    # escape name for subdomain label
    label = quote(name, safe="").lower()
    # some characters are not handled by quote,
    # because they are legal in URLs but not domains,
    # specifically _ and ~ (starting in 3.7).
    # Escape these in the same way (%{hex_codepoint}).
    unique_chars = set(label)
    for c in unique_chars:
        if c not in _dns_needs_replace:
            label = label.replace(c, f"%{ord(c):x}")

    # underscore is our escape char -
    # it's not officially legal in hostnames,
    # but is valid in _domain_ names (?),
    # and seems to always work in practice.
    label = label.replace("%", "_")
    return label
Escape a name for use in a dns label

this is _NOT_ fully domain-safe, but works often enough for realistic usernames.
Fully safe would be full IDNA encoding,
PLUS escaping non-IDNA-legal ascii,
PLUS some encoding of boundary conditions
jupyterhub/utils.py