Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
http.client content length
def _get_content_length(body, method):
# Get the content-length based on the body. If the body is "empty", we
# set Content-Length: 0 for methods that expect a body (RFC 7230,
# Section 3.3.2). If the body is set for other methods, we set the
# header provided we can figure out what the length is.
if not body:
# do an explicit check for not None here to distinguish between unset
# and set but empty
if method.upper() in _METHODS_EXPECTING_BODY or body is not None:
return 0
if hasattr(body, 'read'):
return os.fstat(body.fileno()).st_size
except AttributeError:
# is the object seekable?
curpos = body.tell(), 2)
except (TypeError, AttributeError):
if self.debuglevel > 0:
print('Unable to determine size of %r' % body)
sz = body.tell()
return sz
if hasattr(body, '__iter__'):
# is body a string or bytes type, or another iterable of chars?
except TypeError:
# are we looking at an iterable of ints?
if isinstance(body[0], int):
return len(body)
# nope, this is likely an iterable of iterables
return sum(len(line) for line in body)
return len(body)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.