Skip to content

Commit

Permalink
replace deprecated escape with html.escape
Browse files Browse the repository at this point in the history
  • Loading branch information
davidism committed Apr 12, 2020
1 parent e13b8fb commit 5fd1386
Show file tree
Hide file tree
Showing 10 changed files with 47 additions and 71 deletions.
4 changes: 2 additions & 2 deletions docs/levels.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ user with the name entered.

.. code-block:: python
from werkzeug.utils import escape
from html import escape
from werkzeug.wrappers import Request, Response
@Request.application
Expand All @@ -38,8 +38,8 @@ user with the name entered.
Alternatively the same application could be used without request and response
objects but by taking advantage of the parsing functions werkzeug provides::

from html import escape
from werkzeug.formparser import parse_form_data
from werkzeug.utils import escape

def hello_world(environ, start_response):
result = ['<title>Greeter</title>']
Expand Down
2 changes: 1 addition & 1 deletion examples/plnt/sync.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Does the synchronization. Called by "manage-plnt.py sync"."""
from datetime import datetime
from html import escape

import feedparser
from werkzeug.utils import escape

from .database import Blog
from .database import Entry
Expand Down
2 changes: 1 addition & 1 deletion src/werkzeug/debug/console.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import code
import sys
from html import escape
from types import CodeType

from ..local import Local
from ..utils import escape
from .repr import debug_repr
from .repr import dump
from .repr import helper
Expand Down
3 changes: 1 addition & 2 deletions src/werkzeug/debug/repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@
import re
import sys
from collections import deque
from html import escape
from traceback import format_exception_only

from ..utils import escape


missing = object()
_paragraph_re = re.compile(r"(?:\r\n|\r|\n){2,}")
Expand Down
3 changes: 1 addition & 2 deletions src/werkzeug/debug/tbtools.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@
import sys
import sysconfig
import traceback
from html import escape
from tokenize import TokenError

from .._internal import _to_str
from ..filesystem import get_filesystem_encoding
from ..utils import cached_property
from ..utils import escape
from .console import Console


_coding_re = re.compile(br"coding[:=]\s*([-\w.]+)")
_line_re = re.compile(br"^(.*?)$", re.MULTILINE)
_funcdef_re = re.compile(r"^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)")
Expand Down
2 changes: 1 addition & 1 deletion src/werkzeug/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ def application(environ, start_response):
"""
import sys
from datetime import datetime
from html import escape

from ._internal import _get_environ
from .utils import escape


class HTTPException(Exception):
Expand Down
2 changes: 1 addition & 1 deletion src/werkzeug/testapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
import base64
import os
import sys
from html import escape
from textwrap import wrap

from . import __version__ as _werkzeug_version
from .utils import escape
from .wrappers import BaseRequest as Request
from .wrappers import BaseResponse as Response

Expand Down
47 changes: 20 additions & 27 deletions src/werkzeug/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,14 +211,18 @@ def __init__(self, dialect):
self._dialect = dialect

def __call__(self, s):
import html

warnings.warn(
"'utils.HTMLBuilder' is deprecated and will be removed in 2.1.",
DeprecationWarning,
stacklevel=2,
)
return escape(s)
return html.escape(s)

def __getattr__(self, tag):
import html

warnings.warn(
"'utils.HTMLBuilder' is deprecated and will be removed in 2.1.",
DeprecationWarning,
Expand All @@ -242,7 +246,7 @@ def proxy(*children, **arguments):
else:
value = ""
else:
value = f'="{escape(value)}"'
value = f'="{html.escape(value)}"'
buffer += f" {key}{value}"
if not children and tag in self._empty_elements:
if self._dialect == "xhtml":
Expand All @@ -256,7 +260,7 @@ def proxy(*children, **arguments):

if children_as_string:
if tag in self._plaintext_elements:
children_as_string = escape(children_as_string)
children_as_string = html.escape(children_as_string)
elif tag in self._c_like_cdata and self._dialect == "xhtml":
children_as_string = f"/*<![CDATA[*/{children_as_string}/*]]>*/"
buffer += children_as_string + f"</{tag}>"
Expand Down Expand Up @@ -437,6 +441,8 @@ def escape(s):
.. deprecated:: 2.0
Will be removed in 2.1. Use MarkupSafe instead.
"""
import html

warnings.warn(
"'utils.escape' is deprecated and will be removed in 2.1. Use"
" MarkupSafe instead.",
Expand All @@ -446,18 +452,14 @@ def escape(s):

if s is None:
return ""
elif hasattr(s, "__html__"):

if hasattr(s, "__html__"):
return s.__html__()

if not isinstance(s, str):
s = str(s)

return (
s.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace('"', "&quot;")
)
return html.escape(s, quote=True)


def unescape(s):
Expand All @@ -467,27 +469,15 @@ def unescape(s):
.. deprecated:: 2.0
Will be removed in 2.1. Use MarkupSafe instead.
"""
import html

warnings.warn(
"'utils.unescape' is deprecated and will be removed in 2.1. Use"
" MarkupSafe instead.",
DeprecationWarning,
stacklevel=2,
)

def handle_match(m):
name = m.group(1)
if name in HTMLBuilder._entities:
return chr(HTMLBuilder._entities[name])
try:
if name[:2] in ("#x", "#X"):
return chr(int(name[2:], 16))
elif name.startswith("#"):
return chr(int(name[1:]))
except ValueError:
pass
return ""

return _entity_re.sub(handle_match, s)
return html.unescape(s)


def redirect(location, code=302, Response=None):
Expand All @@ -510,10 +500,12 @@ def redirect(location, code=302, Response=None):
response. The default is :class:`werkzeug.wrappers.Response` if
unspecified.
"""
import html

if Response is None:
from .wrappers import Response

display_location = escape(location)
display_location = html.escape(location)
if isinstance(location, str):
# Safe conversion is necessary here as we might redirect
# to a broken URI scheme (for instance itms-services).
Expand All @@ -525,7 +517,8 @@ def redirect(location, code=302, Response=None):
"<title>Redirecting...</title>\n"
"<h1>Redirecting...</h1>\n"
"<p>You should be redirected automatically to target URL: "
f'<a href="{escape(location)}">{display_location}</a>. If not click the link.',
f'<a href="{html.escape(location)}">{display_location}</a>. If'
" not click the link.",
code,
mimetype="text/html",
)
Expand Down
37 changes: 19 additions & 18 deletions tests/test_debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,25 @@
class TestDebugRepr:
def test_basic_repr(self):
assert debug_repr([]) == "[]"
assert (
debug_repr([1, 2])
== '[<span class="number">1</span>, <span class="number">2</span>]'
assert debug_repr([1, 2]) == (
'[<span class="number">1</span>, <span class="number">2</span>]'
)
assert (
debug_repr([1, "test"])
== '[<span class="number">1</span>, <span class="string">\'test\'</span>]'
assert debug_repr([1, "test"]) == (
'[<span class="number">1</span>,'
' <span class="string">&#x27;test&#x27;</span>]'
)
assert debug_repr([None]) == '[<span class="object">None</span>]'

def test_string_repr(self):
assert debug_repr("") == "<span class=\"string\">''</span>"
assert debug_repr("foo") == "<span class=\"string\">'foo'</span>"
assert debug_repr("") == '<span class="string">&#x27;&#x27;</span>'
assert debug_repr("foo") == '<span class="string">&#x27;foo&#x27;</span>'
assert debug_repr("s" * 80) == (
f'<span class="string">\'{"s" * 69}'
f'<span class="extended">{"s" * 11}\'</span></span>'
f'<span class="string">&#x27;{"s" * 69}'
f'<span class="extended">{"s" * 11}&#x27;</span></span>'
)
assert debug_repr("<" * 80) == (
f'<span class="string">\'{"&lt;" * 69}'
f'<span class="extended">{"&lt;" * 11}\'</span></span>'
f'<span class="string">&#x27;{"&lt;" * 69}'
f'<span class="extended">{"&lt;" * 11}&#x27;</span></span>'
)

def test_string_subclass_repr(self):
Expand All @@ -50,7 +49,7 @@ class Test(str):

assert debug_repr(Test("foo")) == (
'<span class="module">test_debug.</span>'
"Test(<span class=\"string\">'foo'</span>)"
'Test(<span class="string">&#x27;foo&#x27;</span>)'
)

def test_sequence_repr(self):
Expand All @@ -71,7 +70,7 @@ def test_sequence_repr(self):
def test_mapping_repr(self):
assert debug_repr({}) == "{}"
assert debug_repr({"foo": 42}) == (
'{<span class="pair"><span class="key"><span class="string">\'foo\''
'{<span class="pair"><span class="key"><span class="string">&#x27;foo&#x27;'
'</span></span>: <span class="value"><span class="number">42'
"</span></span></span>}"
)
Expand Down Expand Up @@ -109,8 +108,8 @@ def test_mapping_repr(self):
"</span></span></span></span>}"
)
assert debug_repr((1, "zwei", "drei")) == (
'(<span class="number">1</span>, <span class="string">\''
"zwei'</span>, <span class=\"string\">'drei'</span>)"
'(<span class="number">1</span>, <span class="string">&#x27;'
'zwei&#x27;</span>, <span class="string">&#x27;drei&#x27;</span>)'
)

def test_custom_repr(self):
Expand Down Expand Up @@ -143,9 +142,11 @@ def test_regex_repr(self):
def test_set_repr(self):
assert (
debug_repr(frozenset("x"))
== "frozenset([<span class=\"string\">'x'</span>])"
== 'frozenset([<span class="string">&#x27;x&#x27;</span>])'
)
assert debug_repr(set("x")) == (
'set([<span class="string">&#x27;x&#x27;</span>])'
)
assert debug_repr(set("x")) == "set([<span class=\"string\">'x'</span>])"

def test_recursive_repr(self):
a = [1]
Expand Down
16 changes: 0 additions & 16 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,22 +172,6 @@ def test_assign():
assert a.environ["date"] == "Tue, 22 Jan 2008 10:00:00 GMT"


def test_escape():
class Foo(str):
def __html__(self):
return str(self)

assert utils.escape(None) == ""
assert utils.escape(42) == "42"
assert utils.escape("<>") == "&lt;&gt;"
assert utils.escape('"foo"') == "&quot;foo&quot;"
assert utils.escape(Foo("<foo>")) == "<foo>"


def test_unescape():
assert utils.unescape("&lt;&auml;&gt;") == "<ä>"


def test_import_string():
from datetime import date
from werkzeug.debug import DebuggedApplication
Expand Down

0 comments on commit 5fd1386

Please sign in to comment.