#14721 solved setting the Content-Length header for 0-length bodies. However, it doesn't account for cases where body is None (reported by James Rutherford here: http://bugs.python.org/issue14721#msg236600).
One method of solving this might be something like this:
_METHODS_EXPECTING_BODIES = {'OPTIONS', 'POST', 'PUT', 'PATCH'}
if method.upper() in _METHODS_EXPECTING_BODIES and \
'content-length' not in header_names:
self._set_content_length(body)
(_set_content_length would have to be updated in order to allow for None)
This ensures that Content-Length will not be set for methods not expecting a body.
RFC 7230, Section 3.3.2:
A user agent SHOULD NOT send a Content-Length header field when the
request message does not contain a payload body and the method
semantics do not anticipate such a body. |