summaryrefslogtreecommitdiffstats
path: root/Lib/http
diff options
context:
space:
mode:
authorMartin Panter <vadmium+py@gmail.com>2016-02-09 10:20:52 (GMT)
committerMartin Panter <vadmium+py@gmail.com>2016-02-09 10:20:52 (GMT)
commit44391481d7d302bbe1c9c9eb0518b6a45f21e0b9 (patch)
tree4f38a3f7621411a61d1c4a34e8a8e885ca69f8d3 /Lib/http
parent0c0d537b24f66cf16c76ce8f13c21de2ebdbdf44 (diff)
downloadcpython-44391481d7d302bbe1c9c9eb0518b6a45f21e0b9.zip
cpython-44391481d7d302bbe1c9c9eb0518b6a45f21e0b9.tar.gz
cpython-44391481d7d302bbe1c9c9eb0518b6a45f21e0b9.tar.bz2
Issue #26045: Add UTF-8 suggestion to error in http.client
Based on patch by Guido van Rossum.
Diffstat (limited to 'Lib/http')
-rw-r--r--Lib/http/client.py17
1 files changed, 16 insertions, 1 deletions
diff --git a/Lib/http/client.py b/Lib/http/client.py
index 80c80cf..24231b5 100644
--- a/Lib/http/client.py
+++ b/Lib/http/client.py
@@ -146,6 +146,21 @@ _is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
_METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
+def _encode(data, name='data'):
+ """Call data.encode("latin-1") but show a better error message."""
+ try:
+ return data.encode("latin-1")
+ except UnicodeEncodeError as err:
+ raise UnicodeEncodeError(
+ err.encoding,
+ err.object,
+ err.start,
+ err.end,
+ "%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') "
+ "if you want to send it encoded in UTF-8." %
+ (name.title(), data[err.start:err.end], name)) from None
+
+
class HTTPMessage(email.message.Message):
# XXX The only usage of this method is in
# http.server.CGIHTTPRequestHandler. Maybe move the code there so
@@ -1124,7 +1139,7 @@ class HTTPConnection:
if isinstance(body, str):
# RFC 2616 Section 3.7.1 says that text default has a
# default charset of iso-8859-1.
- body = body.encode('iso-8859-1')
+ body = _encode(body, 'body')
self.endheaders(body)
def getresponse(self):