# HG changeset patch # Parent 7fe960f1a101feb1108686dc22afef57cebf52dd Issue #26045: Add UTF-8 suggestion to error in http.client Based on patch by Guido van Rossum. diff -r 7fe960f1a101 Lib/http/client.py --- a/Lib/http/client.py Fri Jan 08 01:01:56 2016 -0800 +++ b/Lib/http/client.py Mon Feb 01 21:24:21 2016 +0000 @@ -146,6 +146,21 @@ _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 @@ 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): diff -r 7fe960f1a101 Lib/test/test_httplib.py --- a/Lib/test/test_httplib.py Fri Jan 08 01:01:56 2016 -0800 +++ b/Lib/test/test_httplib.py Mon Feb 01 21:24:21 2016 +0000 @@ -1042,7 +1042,7 @@ # intentionally omitted for simplicity blacklist = {"HTTPMessage", "parse_headers"} for name in dir(client): - if name in blacklist: + if name.startswith("_") or name in blacklist: continue module_object = getattr(client, name) if getattr(module_object, "__module__", None) == "http.client": diff -r 7fe960f1a101 Misc/NEWS --- a/Misc/NEWS Fri Jan 08 01:01:56 2016 -0800 +++ b/Misc/NEWS Mon Feb 01 21:24:21 2016 +0000 @@ -41,6 +41,9 @@ Library ------- +- Issue #26045: Add UTF-8 suggestion to error message when posting a + non-Latin-1 string with http.client. + - Issue #25672: In the ssl module, enable the SSL_MODE_RELEASE_BUFFERS mode option if it is safe to do so.