Skip to content

http_utils

HTTP utility functions for handling range requests, headers, and responses.

This module provides utilities for: - Range request/response handling (partial content) - Header parsing (Content-Length, ETag, Last-Modified, etc.) - HTTP date conversion - Request argument filtering - Convenience functions for GET/HEAD requests with range support

Example
import py_misc_utils.http_utils as hu

hdrs = {'Content-Range': 'bytes 512-1535/4096'}
r = hu.range(hdrs)
assert r == (512, 1535, 4096)

support_ranges(headers)

Check if the server supports range requests.

Parameters:

Name Type Description Default
headers

HTTP response headers dictionary.

required

Returns:

Name Type Description
bool

True if 'bytes' is in Accept-Ranges header.

Example
import py_misc_utils.http_utils as hu

assert hu.support_ranges({'Accept-Ranges': 'bytes'})
assert not hu.support_ranges({'Accept-Ranges': 'none'})
assert not hu.support_ranges({})
Source code in py_misc_utils/http_utils.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def support_ranges(headers):
  """Check if the server supports range requests.

  Args:
    headers: HTTP response headers dictionary.

  Returns:
    bool: True if 'bytes' is in Accept-Ranges header.

  Example:
    import py_misc_utils.http_utils as hu

    assert hu.support_ranges({'Accept-Ranges': 'bytes'})
    assert not hu.support_ranges({'Accept-Ranges': 'none'})
    assert not hu.support_ranges({})
  """
  return 'bytes' in headers.get(ACCEPT_RANGES, '')

content_length(headers, defval=None)

Get content length from headers, checking X-Linked-Size first.

The X-Linked-Size header - as served by some cloud providers to expose the size of compressed content - takes precedence over Content-Length.

Parameters:

Name Type Description Default
headers

HTTP response headers dictionary.

required
defval

Default value if not found (default: None).

None

Returns:

Type Description

Content length as int, or defval.

Example
import py_misc_utils.http_utils as hu

assert hu.content_length({'Content-Length': '128'}) == 128
assert hu.content_length(
    {'X-Linked-Size': '4096', 'Content-Length': '128'}) == 4096
assert hu.content_length({}) is None
assert hu.content_length({}, defval=0) == 0
Source code in py_misc_utils/http_utils.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def content_length(headers, defval=None):
  """Get content length from headers, checking X-Linked-Size first.

  The X-Linked-Size header - as served by some cloud providers to expose
  the size of compressed content - takes precedence over Content-Length.

  Args:
    headers: HTTP response headers dictionary.
    defval: Default value if not found (default: None).

  Returns:
    Content length as int, or defval.

  Example:
    import py_misc_utils.http_utils as hu

    assert hu.content_length({'Content-Length': '128'}) == 128
    assert hu.content_length(
        {'X-Linked-Size': '4096', 'Content-Length': '128'}) == 4096
    assert hu.content_length({}) is None
    assert hu.content_length({}, defval=0) == 0
  """
  if (length := headers.get(XLINKED_SIZE)) is not None:
    return int(length)
  if (length := headers.get(CONTENT_LENGTH)) is not None:
    return int(length)

  return defval

etag(headers, defval=None)

Get ETag from headers, checking X-Linked-ETag first.

Parameters:

Name Type Description Default
headers

HTTP response headers dictionary.

required
defval

Default value if not found (default: None).

None

Returns:

Type Description

ETag string (stripped of quotes), or defval.

Example
import py_misc_utils.http_utils as hu

assert hu.etag({'ETag': '"abc123"'}) == 'abc123'
# Weak validators keep their W/ prefix - only the quotes are stripped.
assert hu.etag({'ETag': 'W/"abc123"'}) == 'W/"abc123'
assert hu.etag({}) is None
assert hu.etag({}, defval='') == ''
Source code in py_misc_utils/http_utils.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def etag(headers, defval=None):
  """Get ETag from headers, checking X-Linked-ETag first.

  Args:
    headers: HTTP response headers dictionary.
    defval: Default value if not found (default: None).

  Returns:
    ETag string (stripped of quotes), or defval.

  Example:
    import py_misc_utils.http_utils as hu

    assert hu.etag({'ETag': '"abc123"'}) == 'abc123'
    # Weak validators keep their W/ prefix - only the quotes are stripped.
    assert hu.etag({'ETag': 'W/"abc123"'}) == 'W/"abc123'
    assert hu.etag({}) is None
    assert hu.etag({}, defval='') == ''
  """
  if (etag_value := headers.get(XLINKED_ETAG)) is not None:
    return etag_value.strip('"\'')
  if (etag_value := headers.get(ETAG)) is not None:
    return etag_value.strip('"\'')

  return defval

last_modified(headers, defval=None)

Get last modified time from headers as epoch timestamp.

Parameters:

Name Type Description Default
headers

HTTP response headers dictionary.

required
defval

Default value if not found (default: None).

None

Returns:

Type Description

Last-Modified time as epoch timestamp (float), or defval.

Example
import py_misc_utils.http_utils as hu

mt = hu.last_modified({'Last-Modified': 'Wed, 21 Oct 2015 07:28:00 GMT'})
assert mt == 1445412480.0
assert hu.last_modified({}) is None
Source code in py_misc_utils/http_utils.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def last_modified(headers, defval=None):
  """Get last modified time from headers as epoch timestamp.

  Args:
    headers: HTTP response headers dictionary.
    defval: Default value if not found (default: None).

  Returns:
    Last-Modified time as epoch timestamp (float), or defval.

  Example:
    import py_misc_utils.http_utils as hu

    mt = hu.last_modified({'Last-Modified': 'Wed, 21 Oct 2015 07:28:00 GMT'})
    assert mt == 1445412480.0
    assert hu.last_modified({}) is None
  """
  if (mtime := headers.get(LAST_MODIFIED)) is not None:
    return date_to_epoch(mtime)

  return defval

add_range(headers, start, end)

Add a Range header to request headers.

Parameters:

Name Type Description Default
headers

Request headers dictionary (modified in place).

required
start

Start byte (inclusive).

required
end

End byte (exclusive).

required

Returns:

Type Description

The modified headers dictionary.

Example
import py_misc_utils.http_utils as hu

headers = hu.add_range({}, 1024, 2048)
assert headers['Range'] == 'bytes=1024-2047'
Source code in py_misc_utils/http_utils.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def add_range(headers, start, end):
  """Add a Range header to request headers.

  Args:
    headers: Request headers dictionary (modified in place).
    start: Start byte (inclusive).
    end: End byte (exclusive).

  Returns:
    The modified headers dictionary.

  Example:
    import py_misc_utils.http_utils as hu

    headers = hu.add_range({}, 1024, 2048)
    assert headers['Range'] == 'bytes=1024-2047'
  """
  headers[RANGE] = f'bytes={start}-{end - 1}'

  return headers

range(headers)

Parse Content-Range header or infer range from Content-Length.

Parameters:

Name Type Description Default
headers

HTTP response headers dictionary.

required

Returns:

Type Description

Range namedtuple (start, stop, length) - where stop is the last byte

offset (inclusive) - or None if not available.

Example
import py_misc_utils.http_utils as hu

r = hu.range({'Content-Range': 'bytes 512-1535/4096'})
assert r == (512, 1535, 4096)
assert r.start == 512 and r.stop == 1535 and r.length == 4096

# Without Content-Range, the range is inferred from Content-Length.
assert hu.range({'Content-Length': '128'}) == (0, 127, 128)
assert hu.range({}) is None
Source code in py_misc_utils/http_utils.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def range(headers):
  """Parse Content-Range header or infer range from Content-Length.

  Args:
    headers: HTTP response headers dictionary.

  Returns:
    Range namedtuple (start, stop, length) - where stop is the last byte
    offset (inclusive) - or None if not available.

  Example:
    import py_misc_utils.http_utils as hu

    r = hu.range({'Content-Range': 'bytes 512-1535/4096'})
    assert r == (512, 1535, 4096)
    assert r.start == 512 and r.stop == 1535 and r.length == 4096

    # Without Content-Range, the range is inferred from Content-Length.
    assert hu.range({'Content-Length': '128'}) == (0, 127, 128)
    assert hu.range({}) is None
  """
  hrange = headers.get(CONTENT_RANGE)
  if hrange is None:
    if (length := content_length(headers)) is not None:
      return Range(start=0, stop=length - 1, length=length)
  else:
    m = re.match(r'bytes\s+(\d+)\-(\d+)(/(\d+))?', hrange)
    if m:
      hlength = m.group(4)
      length = int(hlength) if hlength else None

      return Range(start=int(m.group(1)), stop=int(m.group(2)), length=length)

range_data(start, stop, headers, data)

Return the slice of data matching a possibly clipped range.

Parameters:

Name Type Description Default
start

The requested start offset.

required
stop

The requested stop offset (inclusive).

required
headers

The response headers holding the range actually served - as parsed by the range() helper.

required
data

The contents served by the response, covering the served range.

required

Returns:

Type Description

The data slice matching the requested range, or the data itself when

no clipping is needed.

Raises:

Type Description
ValueError

If the requested range is not covered by the served range.

Example
import py_misc_utils.http_utils as hu

data = b'0123456789'
hdrs = {'Content-Range': 'bytes 2-5/10'}

assert bytes(hu.range_data(2, 5, hdrs, b'2345')) == b'2345'
# A sub-range of the served range is clipped out of it.
assert bytes(hu.range_data(2, 3, hdrs, b'2345')) == b'23'
# Without Content-Range the whole data is served - and returned.
assert bytes(hu.range_data(0, 9, {}, data)) == data
Source code in py_misc_utils/http_utils.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def range_data(start, stop, headers, data):
  """Return the slice of data matching a possibly clipped range.

  Args:
    start: The requested start offset.
    stop: The requested stop offset (inclusive).
    headers: The response headers holding the range actually served - as
      parsed by the range() helper.
    data: The contents served by the response, covering the served range.

  Returns:
    The data slice matching the requested range, or the data itself when
    no clipping is needed.

  Raises:
    ValueError: If the requested range is not covered by the served range.

  Example:
    import py_misc_utils.http_utils as hu

    data = b'0123456789'
    hdrs = {'Content-Range': 'bytes 2-5/10'}

    assert bytes(hu.range_data(2, 5, hdrs, b'2345')) == b'2345'
    # A sub-range of the served range is clipped out of it.
    assert bytes(hu.range_data(2, 3, hdrs, b'2345')) == b'23'
    # Without Content-Range the whole data is served - and returned.
    assert bytes(hu.range_data(0, 9, {}, data)) == data
  """
  hrange = range(headers)
  if hrange is not None:
    if start < hrange.start or stop > hrange.stop:
      from . import alog

      alog.xraise(ValueError,
                  f'Requested range [{start}, {stop}] not covered by served '
                  f'range [{hrange.start}, {hrange.stop}]')

    dstart = start - hrange.start
    size = min(stop - start, hrange.stop - hrange.start) + 1
    dstop = dstart + size - 1

    if dstart != 0 or dstop != len(data) - 1:
      return memoryview(data)[dstart:dstop + 1]

  return data

date_to_epoch(http_date)

Convert HTTP date string to epoch timestamp.

Parameters:

Name Type Description Default
http_date

Date string in HTTP format (e.g., 'Mon, 01 Jan 2024 00:00:00 GMT').

required

Returns:

Type Description

Epoch timestamp as int.

Example
import py_misc_utils.http_utils as hu

assert hu.date_to_epoch('Wed, 21 Oct 2015 07:28:00 GMT') == 1445412480
Source code in py_misc_utils/http_utils.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
def date_to_epoch(http_date):
  """Convert HTTP date string to epoch timestamp.

  Args:
    http_date: Date string in HTTP format (e.g., 'Mon, 01 Jan 2024 00:00:00 GMT').

  Returns:
    Epoch timestamp as int.

  Example:
    import py_misc_utils.http_utils as hu

    assert hu.date_to_epoch('Wed, 21 Oct 2015 07:28:00 GMT') == 1445412480
  """
  htime = time.strptime(http_date, _HTTP_DATE_FMT)

  return calendar.timegm(htime)

epoch_to_date(epoch_time=None)

Convert epoch timestamp to HTTP date string.

Parameters:

Name Type Description Default
epoch_time

Epoch timestamp (default: current time).

None

Returns:

Type Description

Date string in HTTP format (e.g., 'Mon, 01 Jan 2024 00:00:00 GMT').

Example
import py_misc_utils.http_utils as hu

assert hu.epoch_to_date(1445412480) == 'Wed, 21 Oct 2015 07:28:00 GMT'
# Round-trips with date_to_epoch().
assert hu.date_to_epoch(hu.epoch_to_date(1445412480)) == 1445412480
Source code in py_misc_utils/http_utils.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def epoch_to_date(epoch_time=None):
  """Convert epoch timestamp to HTTP date string.

  Args:
    epoch_time: Epoch timestamp (default: current time).

  Returns:
    Date string in HTTP format (e.g., 'Mon, 01 Jan 2024 00:00:00 GMT').

  Example:
    import py_misc_utils.http_utils as hu

    assert hu.epoch_to_date(1445412480) == 'Wed, 21 Oct 2015 07:28:00 GMT'
    # Round-trips with date_to_epoch().
    assert hu.date_to_epoch(hu.epoch_to_date(1445412480)) == 1445412480
  """
  return time.strftime(_HTTP_DATE_FMT,
                       time.gmtime(time.time() if epoch_time is None else epoch_time))

filter_request_args(kwargs, key=None)

Extract requests-compatible arguments from a keyword dictionary.

Parameters:

Name Type Description Default
kwargs

Dictionary containing request parameters - only the known requests arguments (headers, timeout, auth, cookies, allow_redirects, proxies, verify, cert) are picked up.

required
key

Key in kwargs holding a pre-built requests kwargs dict, which is returned as-is (default: 'requests').

None

Returns:

Type Description

The requests-compatible arguments dictionary.

Example
import py_misc_utils.http_utils as hu

args = hu.filter_request_args(
    {'headers': {'X-Token': 'tok'}, 'timeout': 4.0, 'bogus': 'x'})
assert args == {'headers': {'X-Token': 'tok'}, 'timeout': 4.0}

# A pre-built requests dict, under key, is returned as-is.
args2 = hu.filter_request_args({'client': {'headers': {'a': 'b'}}},
                                key='client')
assert args2 == {'headers': {'a': 'b'}}
Source code in py_misc_utils/http_utils.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def filter_request_args(kwargs, key=None):
  """Extract requests-compatible arguments from a keyword dictionary.

  Args:
    kwargs: Dictionary containing request parameters - only the known
      requests arguments (headers, timeout, auth, cookies, allow_redirects,
      proxies, verify, cert) are picked up.
    key: Key in kwargs holding a pre-built requests kwargs dict, which is
      returned as-is (default: 'requests').

  Returns:
    The requests-compatible arguments dictionary.

  Example:
    import py_misc_utils.http_utils as hu

    args = hu.filter_request_args(
        {'headers': {'X-Token': 'tok'}, 'timeout': 4.0, 'bogus': 'x'})
    assert args == {'headers': {'X-Token': 'tok'}, 'timeout': 4.0}

    # A pre-built requests dict, under key, is returned as-is.
    args2 = hu.filter_request_args({'client': {'headers': {'a': 'b'}}},
                                    key='client')
    assert args2 == {'headers': {'a': 'b'}}
  """
  req_kwargs = kwargs.get(key or 'requests')
  if req_kwargs is None:
    req_kwargs = dict()
    for arg in ('headers', 'timeout', 'auth', 'cookies', 'allow_redirects', 'proxies',
                'verify', 'cert'):
      argv = kwargs.get(arg)
      if argv is not None:
        req_kwargs[arg] = argv

  return req_kwargs

info(url, mod=None, headers=None, **kwargs)

Get file metadata (size, ETag, Last-Modified) using HEAD or range GET.

Attempts a GET request with a small range (0-1023) first to detect range support and get metadata. Falls back to HEAD if range request fails.

Parameters:

Name Type Description Default
url

URL to request.

required
mod

The requests-like module used to perform the requests (default: requests). For testing, any object with get()/head() methods returning a requests-like response can be passed.

None
headers

Optional request headers (default: empty dict).

None
**kwargs

Additional arguments passed to mod.get()/mod.head().

{}

Returns:

Type Description

The response of the metadata request - with Content-Length holding the

file size, and possibly ETag and Last-Modified headers populated.

Example
import py_misc_utils.http_utils as hu


class FakeResp:
  def __init__(self, headers, content):
    self.headers = headers
    self.content = content

  def raise_for_status(self):
    pass


class FakeMod:
  def __init__(self, headers, content):
    self.headers = headers
    self.content = content

  def get(self, url, **kwargs):
    return FakeResp(self.headers, self.content)

  def head(self, url, **kwargs):
    return FakeResp(self.headers, b'')


mod = FakeMod({'Content-Range': 'bytes 0-1023/8192',
               'ETag': '"v1"',
               'Last-Modified': 'Wed, 21 Oct 2015 07:28:00 GMT'},
              b'x' * 1024)
info = hu.info('http://host/data.bin', mod=mod)
assert info.headers['Content-Length'] == 8192
assert hu.etag(info.headers) == 'v1'
assert hu.last_modified(info.headers) == 1445412480
Source code in py_misc_utils/http_utils.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
def info(url, mod=None, headers=None, **kwargs):
  """Get file metadata (size, ETag, Last-Modified) using HEAD or range GET.

  Attempts a GET request with a small range (0-1023) first to detect range
  support and get metadata. Falls back to HEAD if range request fails.

  Args:
    url: URL to request.
    mod: The requests-like module used to perform the requests (default:
      requests). For testing, any object with get()/head() methods
      returning a requests-like response can be passed.
    headers: Optional request headers (default: empty dict).
    **kwargs: Additional arguments passed to mod.get()/mod.head().

  Returns:
    The response of the metadata request - with Content-Length holding the
    file size, and possibly ETag and Last-Modified headers populated.

  Example:
    import py_misc_utils.http_utils as hu


    class FakeResp:
      def __init__(self, headers, content):
        self.headers = headers
        self.content = content

      def raise_for_status(self):
        pass


    class FakeMod:
      def __init__(self, headers, content):
        self.headers = headers
        self.content = content

      def get(self, url, **kwargs):
        return FakeResp(self.headers, self.content)

      def head(self, url, **kwargs):
        return FakeResp(self.headers, b'')


    mod = FakeMod({'Content-Range': 'bytes 0-1023/8192',
                   'ETag': '"v1"',
                   'Last-Modified': 'Wed, 21 Oct 2015 07:28:00 GMT'},
                  b'x' * 1024)
    info = hu.info('http://host/data.bin', mod=mod)
    assert info.headers['Content-Length'] == 8192
    assert hu.etag(info.headers) == 'v1'
    assert hu.last_modified(info.headers) == 1445412480
  """
  mod = mod or requests
  req_headers = headers.copy() if headers else dict()

  add_range(req_headers, 0, 1024)

  try:
    resp = mod.get(url, headers=req_headers, **kwargs)
    resp.raise_for_status()

    hrange = range(resp.headers)
    if hrange is not None and hrange.length is not None and CONTENT_RANGE in resp.headers:
      resp.headers[CONTENT_LENGTH] = hrange.length
      resp.headers[ACCEPT_RANGES] = 'bytes'
    else:
      resp = None
  except requests.exceptions.HTTPError:
    resp = None

  if resp is None:
    resp = mod.head(url, headers=headers, **kwargs)
    resp.raise_for_status()

  return resp

get(url, mod=None, **kwargs)

Send a GET request and return the response content.

Parameters:

Name Type Description Default
url

URL to request.

required
mod

HTTP module to use (default: requests).

None
**kwargs

Additional arguments passed to mod.get().

{}

Returns:

Type Description

Response content as bytes.

Raises:

Type Description
HTTPError

If the server returns an error status.

Example
import py_misc_utils.http_utils as hu


class FakeResp:
  def __init__(self, content):
    self.content = content

  def raise_for_status(self):
    pass


class FakeMod:
  def get(self, url, **kwargs):
    return FakeResp(b'fake-payload')

assert hu.get('http://host/data.bin', mod=FakeMod()) == b'fake-payload'
Source code in py_misc_utils/http_utils.py
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
def get(url, mod=None, **kwargs):
  """Send a GET request and return the response content.

  Args:
    url: URL to request.
    mod: HTTP module to use (default: requests).
    **kwargs: Additional arguments passed to mod.get().

  Returns:
    Response content as bytes.

  Raises:
    requests.exceptions.HTTPError: If the server returns an error status.

  Example:
    import py_misc_utils.http_utils as hu


    class FakeResp:
      def __init__(self, content):
        self.content = content

      def raise_for_status(self):
        pass


    class FakeMod:
      def get(self, url, **kwargs):
        return FakeResp(b'fake-payload')

    assert hu.get('http://host/data.bin', mod=FakeMod()) == b'fake-payload'
  """
  mod = mod or requests

  resp = mod.get(url, **kwargs)
  resp.raise_for_status()

  return resp.content