Skip to content

Instantly share code, notes, and snippets.

@demianbrecht
Created March 31, 2015 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save demianbrecht/f94be5a51e32bb9c81e1 to your computer and use it in GitHub Desktop.
Save demianbrecht/f94be5a51e32bb9c81e1 to your computer and use it in GitHub Desktop.
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