Skip to content

Instantly share code, notes, and snippets.

Embed
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
return
if hasattr(body, 'read'):
try:
return os.fstat(body.fileno()).st_size
except AttributeError:
# is the object seekable?
try:
curpos = body.tell()
body.seek(0, 2)
except (TypeError, AttributeError):
if self.debuglevel > 0:
print('Unable to determine size of %r' % body)
return
else:
sz = body.tell()
body.seek(curpos)
return sz
if hasattr(body, '__iter__'):
try:
# is body a string or bytes type, or another iterable of chars?
ord(body[0])
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)
else:
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.