source code of /htmlescape.py

Last modified
Lines 64

Parent directory Download CGIread sitemap Main page

Quick links: escape escape_core

  1. #!/usr/bin/python
  2. def escape_core(level, text):
  3.     '''
  4.     Used by `escape`
  5.     
  6.     Levels of escaping
  7.     ------------------
  8.     
  9.         `level` == 0: No treatment.
  10.         `level` == 1: '<', '>' and '&'
  11.         `level` == 2: '<', '>', '&', '"' and "'"
  12.     '''
  13.     text = '{}'.format(text)
  14.     if level == 0:
  15.         return text
  16.     elif level >= 1:
  17.         escaped = text.replace(
  18.             '&', '&amp;').replace(
  19.             '<', '&lt;').replace(
  20.             '>', '&gt;'
  21.         )
  22.         if level == 1:
  23.             return escaped
  24.         elif level >= 2:
  25.             return escaped.replace('"', '&quot;').replace("'", '&apos;')
  26.         else:
  27.             assert False, "Level too high."
  28. def escape(s, *args, **kwargs):
  29.     '''
  30.     (CGI) escaping replacement for `str.format`.
  31.     
  32.     escape('<a href={}>{}</a>',
  33.         2, 'http://example.com/',
  34.         1, 'example.com',
  35.     )
  36.     
  37.     Arguments: s [level text] ... [key=(level, text)] ...
  38.     
  39.     Levels of escaping
  40.     ------------------
  41.     
  42.         `level` == 0: No treatment.
  43.         `level` == 1: '<', '>' and '&'
  44.         `level` == 2: '<', '>', '&', '"' and "'"
  45.     '''
  46.     assert len(args)%2 == 0
  47.     
  48.     args = list(args) # Needed for `pop`ping.
  49.     
  50.     safe_args = []
  51.     while args:
  52.         level = args.pop(0)
  53.         text = args.pop(0)
  54.         safe_args.append(escape_core(level, text))
  55.     
  56.     safe_kwargs = {}
  57.     for key in kwargs:
  58.         safe_kwargs[key] = escape_core(kwargs[key][0], kwargs[key][1])
  59.     
  60.     return s.format(*safe_args, **safe_kwargs)