Created
March 31, 2015 16:40
-
-
Save demianbrecht/f94be5a51e32bb9c81e1 to your computer and use it in GitHub Desktop.
http.client content length
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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