Range Headers Parse To Slices
Turn HTTP Range headers into safe (start, end) slices: suffix and open-ended forms clamp to the body size, and malformed ranges resolve to None.
Code
def parse_range(header, size):
# "bytes=<start>-<end>":end 可省略(到末尾),start 可省略(后缀语义)
unit, _, spec = header.partition("=")
if unit != "bytes" or not spec:
return None
start_s, _, end_s = spec.partition("-")
if start_s == "": # bytes=-500:最后 500 字节
start = max(0, size - int(end_s))
end = size - 1
else:
start = int(start_s)
end = size - 1 if end_s == "" else min(int(end_s), size - 1)
if start > end or start >= size:
return None # 越界区间交给 416 处理
return start, end
SIZE = 1024
for header in ["bytes=0-99", "bytes=100-", "bytes=-256", "bytes=0-99999", "bytes=2000-3000", "items=0-5"]:
print(header, "->", parse_range(header, SIZE))
# 端闭区间换算成切片长度:end - start + 1
rng = parse_range("bytes=100-", SIZE)
print("slice length:", rng[1] - rng[0] + 1)Output
Captured from a sandboxed run of this snippet in the build pipeline.
bytes=0-99 -> (0, 99)
bytes=100- -> (100, 1023)
bytes=-256 -> (768, 1023)
bytes=0-99999 -> (0, 1023)
bytes=2000-3000 -> None
items=0-5 -> None
slice length: 924Inside the snippet
Count the function parse_range as the entire surface area of Range Headers Parse To Slices.
Repetition is confined to for header in ["bytes=0-99", "bytes=100-", "bytes=-256", "bytes=0-99999", "bytes=2000-3000", "ite… — the rest of the file is straight-line.
Using it
Entry signature: def parse_range(header, size)
Running the file prints labeled results such as slice length: — each operation’s effect is visible in the output.
Callers only need parse_range — everything else stays internal.
Interactive Tools for This Topic
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `parse_range` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.