def escape(s, quote=None):
    """Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true, the quotation mark character (")
    is also translated.

    This is the same as cgi.escape in Python, but always operates on
    bytes, whereas cgi.escape in Python 3 only works on unicodes.
    """
    s = s.replace(b'&', b'&amp;')
    s = s.replace(b'<', b'&lt;')
    s = s.replace(b'>', b'&gt;')
    if quote:
        s = s.replace(b'"', b'&quot;')
    return s
