def local_html_escape(data, quote=False):
 if PY2:
  import cgi
  data = cgi.escape(data, quote)
  return (data.replace("'", '&#x27;') if quote else data)
 else:
  import html
  if isinstance(data, str):
   return html.escape(data, quote=quote)
  data = data.replace('&', '&amp;')
  data = data.replace('<', '&lt;')
  data = data.replace('>', '&gt;')
  if quote:
   data = data.replace('"', '&quot;')
   data = data.replace("'", '&#x27;')
  return data

def local_html_escape ( data , quote = False ) : if PY2 : import cgi data = cgi . escape ( data , quote ) return ( data . replace ( "'" , '&#x27;' ) if quote else data ) else : import html if isinstance ( data , str ) : return html . escape ( data , quote = quote ) data = data . replace ( '&' , '&amp;' ) data = data . replace ( '<' , '&lt;' ) data = data . replace ( '>' , '&gt;' ) if quote : data = data . replace ( '"' , '&quot;' ) data = data . replace ( "'" , '&#x27;' ) return data
works with bytes .