#2830: add html.escape() helper and move cgi.escape() uses in the standard library to it. It defaults to quote=True and also escapes single quotes, which makes casual use safer. The cgi.escape() interface is not touched, but emits a (silent) PendingDeprecationWarning.
diff --git a/Lib/cgi.py b/Lib/cgi.py
index 7da2b23..8786e58 100755
--- a/Lib/cgi.py
+++ b/Lib/cgi.py
@@ -31,13 +31,13 @@
# Imports
# =======
-from operator import attrgetter
from io import StringIO
import sys
import os
import urllib.parse
import email.parser
from warnings import warn
+import html
__all__ = ["MiniFieldStorage", "FieldStorage",
"parse", "parse_qs", "parse_qsl", "parse_multipart",
@@ -800,8 +800,8 @@
list = traceback.format_tb(tb, limit) + \
traceback.format_exception_only(type, value)
print("<PRE>%s<B>%s</B></PRE>" % (
- escape("".join(list[:-1])),
- escape(list[-1]),
+ html.escape("".join(list[:-1])),
+ html.escape(list[-1]),
))
del tb
@@ -812,7 +812,7 @@
print("<H3>Shell Environment:</H3>")
print("<DL>")
for key in keys:
- print("<DT>", escape(key), "<DD>", escape(environ[key]))
+ print("<DT>", html.escape(key), "<DD>", html.escape(environ[key]))
print("</DL>")
print()
@@ -825,10 +825,10 @@
print("<P>No form fields.")
print("<DL>")
for key in keys:
- print("<DT>" + escape(key) + ":", end=' ')
+ print("<DT>" + html.escape(key) + ":", end=' ')
value = form[key]
- print("<i>" + escape(repr(type(value))) + "</i>")
- print("<DD>" + escape(repr(value)))
+ print("<i>" + html.escape(repr(type(value))) + "</i>")
+ print("<DD>" + html.escape(repr(value)))
print("</DL>")
print()
@@ -839,9 +839,9 @@
try:
pwd = os.getcwd()
except os.error as msg:
- print("os.error:", escape(str(msg)))
+ print("os.error:", html.escape(str(msg)))
else:
- print(escape(pwd))
+ print(html.escape(pwd))
print()
def print_arguments():
@@ -899,9 +899,9 @@
# =========
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.'''
+ """Deprecated API."""
+ warn("cgi.escape is deprecated, use html.escape instead",
+ PendingDeprecationWarning, stacklevel=2)
s = s.replace("&", "&") # Must be done first!
s = s.replace("<", "<")
s = s.replace(">", ">")
@@ -909,6 +909,7 @@
s = s.replace('"', """)
return s
+
def valid_boundary(s, _vb_pattern="^[ -~]{0,200}[!-~]$"):
import re
return re.match(_vb_pattern, s)