MCPcopy
hub / github.com/encode/httpx / peek_filelike_length

Function peek_filelike_length

httpx/_utils.py:95–117  ·  view source on GitHub ↗

Given a file-like stream object, return its length in number of bytes without reading it into memory.

(stream: typing.Any)

Source from the content-addressed store, hash-verified

93
94
95def peek_filelike_length(stream: typing.Any) -> int | None:
96 """
97 Given a file-like stream object, return its length in number of bytes
98 without reading it into memory.
99 """
100 try:
101 # Is it an actual file?
102 fd = stream.fileno()
103 # Yup, seems to be an actual file.
104 length = os.fstat(fd).st_size
105 except (AttributeError, OSError):
106 # No... Maybe it's something that supports random access, like `io.BytesIO`?
107 try:
108 # Assuming so, go to end of stream to figure out its length,
109 # then put it back in place.
110 offset = stream.tell()
111 length = stream.seek(0, os.SEEK_END)
112 stream.seek(offset)
113 except (AttributeError, OSError):
114 # Not even that? Sorry, we're doomed...
115 return None
116
117 return length
118
119
120class URLPattern:

Callers 2

encode_contentFunction · 0.85
get_lengthMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected