A proxy connection drops halfway through a dataset export. The partial file is still on disk. Should the next request append to it or start again?

I would make that decision from the response and the file version, not from the presence of a .part file. Resume only when the returned byte range matches the local offset and the request is protected against a changed representation. If the server sends a full 200 response, replace the partial download instead of appending it. Publish the final filename only after a trusted digest matches.

This guide is for developers downloading authorized exports, reports, or public datasets. It uses Python Requests, one local writer, a single byte range, an identity-encoded response, and a trusted SHA-256 for the exact file version. It is not a general browser downloader. Respect source permissions, download limits, and the data provider's retention requirements.

Decide whether resuming is worth supporting

For a small export, restarting is often the simpler recovery path. Resuming becomes useful when repeated full transfers consume meaningful time or data and the source offers stable file versions. The important procurement question is whether the complete download workflow supports recovery; a proxy advertised as long-lived does not establish that the source supports byte ranges.

ConditionDecision for this implementationReason
Partial file plus a saved strong ETag for the same request contextRequest the remaining bytesThe validator protects the selected representation
Missing metadata, a weak ETag, or a different contextStart a full downloadThe partial bytes cannot safely be attributed to the requested version
Range request receives valid 206Append after validating its rangeA partial response needs an explicit offset check
Range request receives 200Truncate the partial file and write the full responseThe server may ignore Range, or the version may have changed
Response is 416, malformed, or content-encodedStop and investigateThe sample cannot safely combine that response
Downloaded file fails the trusted SHA-256Keep the existing final file unchangedLength alone does not establish correct content

If the failure occurs before any body arrives, first use the proxy timeout diagnosis guide to identify the failed stage. The code below addresses file recovery after receiving bytes; it does not diagnose the network path.

Keep byte offsets and representation versions together

If 65,536 bytes have actually reached disk, Range: bytes=65536- requests the next byte onward. Byte positions are zero-based. A returned Content-Range: bytes 65536-99999/100000 identifies the inclusive interval and the complete representation length. Do not confuse the last byte position with the number of bytes in the response.

RFC 9110 sections 13.1.5 and 14 define If-Range and range handling. A server may ignore Range, and Accept-Ranges: bytes does not guarantee the next response will be partial. Inspect the actual response every time.

Send a saved strong ETag in If-Range. Do not strip its quotes, replace it with a locally invented digest, or send a weak tag such as W/"version-1". This sample deliberately does not use Last-Modified as a fallback: a date is suitable for If-Range only under the standard's strong-validator conditions, which this downloader does not establish.

That differs from conditional GET with 304 handling. A conditional GET reuses a complete saved response; a range request obtains missing bytes and must protect the combination of old and new bytes.

Compression matters here. Requests can decode compressed content while streaming it. A local decoded-byte count must not be blindly used as an offset into an encoded representation. The sample requests Accept-Encoding: identity and rejects any non-identity Content-Encoding before opening the partial file. This is a deliberate compatibility restriction, not a requirement for every HTTP downloader.

A bounded implementation: one call, one request

Save this as resume_download.py. It requires Requests and a writable destination directory. The expected SHA-256 must come from a trusted manifest or another authenticated source for this exact version. Computing a hash from the same unchecked download does not supply an independent expected value.

import hashlib
import json
import re
from pathlib import Path


def download_once(session, url, destination, expected_sha256, context_id):
    """One request per call; single writer, fixed request context, identity only."""
    if not re.fullmatch(r"[0-9a-fA-F]{64}", expected_sha256):
        raise ValueError("Supply a trusted SHA-256 for this exact file version")
    destination = Path(destination)
    part = destination.with_name(destination.name + ".part")
    meta = destination.with_name(destination.name + ".part.json")
    key = hashlib.sha256(
        (url + "\n" + context_id + "\n" + expected_sha256.lower()).encode("utf-8")
    ).hexdigest()
    state = {}
    if meta.exists():
        try:
            state = json.loads(meta.read_text(encoding="utf-8"))
        except (ValueError, OSError):
            state = {}
    offset = part.stat().st_size if part.exists() else 0
    etag = state.get("etag", "")
    strong = bool(re.fullmatch(r'"[\x21\x23-\x7e\x80-\xff]*"', etag))
    resume = offset > 0 and state.get("key") == key and strong
    headers = {"Accept-Encoding": "identity"}
    if resume:
        headers.update({"Range": f"bytes={offset}-", "If-Range": etag})
    with session.get(url, headers=headers, stream=True,
                     allow_redirects=False, timeout=(10, 30)) as response:
        if response.status_code == 416:
            raise ValueError("416: inspect version and local file; do not mark complete")
        response.raise_for_status()
        if response.headers.get("Content-Encoding", "identity").lower() != "identity":
            raise ValueError("Encoded representation refused before file write")
        received_etag = response.headers.get("ETag", "")
        if response.status_code == 206 and resume:
            match = re.fullmatch(r"bytes (\d+)-(\d+)/(\d+)",
                                 response.headers.get("Content-Range", ""))
            if not match:
                raise ValueError("Unsupported or invalid Content-Range")
            start, end, total = map(int, match.groups())
            if start != offset or not start <= end < total:
                raise ValueError("Range does not match local offset")
            if received_etag and received_etag != etag:
                raise ValueError("Validator changed in partial response")
            expected_body = end - start + 1
            mode = "ab"
        elif response.status_code == 200:
            offset = 0
            total = None
            expected_body = None
            mode = "wb"
        else:
            raise ValueError("Expected full 200 or requested single-part 206")
        length = response.headers.get("Content-Length")
        if length is not None:
            if not re.fullmatch(r"\d+", length):
                raise ValueError("Invalid Content-Length")
            if expected_body is not None and int(length) != expected_body:
                raise ValueError("Content-Length conflicts with range")
            expected_body = int(length)
            if response.status_code == 200:
                total = expected_body
        # Open/truncate before replacing metadata. One process owns these paths.
        with part.open(mode) as output:
            next_state = {"key": key, "etag": received_etag or (etag if resume else "")}
            temporary = meta.with_name(meta.name + ".new")
            temporary.write_text(json.dumps(next_state), encoding="utf-8")
            temporary.replace(meta)
            written = 0
            for chunk in response.iter_content(chunk_size=65536):
                if not chunk:
                    continue
                if expected_body is not None and written + len(chunk) > expected_body:
                    output.truncate(offset)
                    raise ValueError("Response exceeds declared byte count")
                output.write(chunk)
                written += len(chunk)
        if expected_body is not None and written != expected_body:
            raise ValueError("Incomplete response: partial file retained")
        if total is not None and part.stat().st_size != total:
            raise ValueError("Still partial: call again after checking the response")
    digest = hashlib.sha256()
    with part.open("rb") as saved:
        for chunk in iter(lambda: saved.read(65536), b""):
            digest.update(chunk)
    if digest.hexdigest() != expected_sha256.lower():
        meta.unlink(missing_ok=True)  # next call starts over
        raise ValueError("SHA-256 mismatch: final file was not replaced")
    part.replace(destination)
    meta.unlink(missing_ok=True)
    return destination

The function performs one request per call. A connection exception propagates, while bytes already written remain in the partial file. A later, explicitly scheduled call can resume. There is no unbounded retry loop and no automatic promotion of a 416 response to success.

Use it from a separately configured session:

import os
import requests
from resume_download import download_once

with requests.Session() as session:
    session.trust_env = False
    # Optional: load an approved proxy URL from your own secret store.
    proxy_url = os.environ.get("APP_DOWNLOAD_PROXY")
    if proxy_url:
        session.proxies.update({"http": proxy_url, "https": proxy_url})
    download_once(
        session,
        os.environ["EXPORT_URL"],
        "dataset.csv",
        os.environ["EXPORT_SHA256"],
        context_id="public-export-v1-en",
    )

EXPORT_URL and EXPORT_SHA256 are real inputs you must supply, not literal example values. APP_DOWNLOAD_PROXY is optional; omit it for a direct request. Keep credentials out of terminal history and shared logs. For the meaning of the two proxy mapping keys, see HTTP proxy configuration in Python.

context_id names the stable representation-selection context: account scope, language, export parameters, and relevant region. It is not a password. Change it when those conditions change. Keep source headers and cookies fixed between attempts. The sidecar stores a fingerprint of the URL, context, and digest instead of the URL itself; nevertheless, protect both metadata and downloaded data with appropriate local permissions.

Check the final file before downstream processing

The sample promotes dataset.csv.part to dataset.csv only after the expected digest matches. An existing final file survives a failed download or digest mismatch. A failed digest removes the resume metadata so the next call starts over; it does not silently reuse the rejected bytes.

Length checks detect some incomplete transfers, but not every corruption or wrong-version response. SHA-256 matching a trusted expected value checks byte identity; it does not establish that the source data is accurate, current, or authorized for a particular use. Parse and validate the export after download as a separate acceptance step.

The code also stops on redirects, multipart ranges, unknown complete lengths in a 206, and unexpected successful status codes. For a signed URL that expires or changes, resolve the new authorized URL and file version deliberately. Do not keep refreshing URLs or rotating proxies until an access denial disappears.

A Requests read timeout is not an overall job deadline. Schedule retries with an attempt limit and elapsed-time budget appropriate to the export, and honor source throttling. Closing the response releases its resources; HTTP connection pooling is a separate concern from whether the partial file is reusable.

What was verified

The included function was exercised with Python 3.11.15 and Requests 2.34.2 against local HTTP fixtures. Ten download checks covered a full 200, valid 206 append, ignored Range, a changed-version full response, interruption followed by resume, an incorrect range start, 416, an encoded response, a weak ETag, and digest mismatch protecting an existing final file.

These checks validate the demonstrated branches. They do not measure any live proxy, public dataset host, throughput, or provider availability. The implementation assumes one process owns the paths and local partial files are not edited. It is not a filesystem transaction across crashes or concurrent workers. For a large production workflow, add locking, durable job state, quota checks, and source-specific response validation before deployment.

Frequently asked questions

Is Accept-Ranges enough to enable append mode?

No. It is advisory. Validate the actual 206 Content-Range and version protection. A full 200 must never be appended to the old partial file.

Can a weak ETag protect a resumed file?

Not with If-Range. The standard forbids a weak entity tag in that request field. This implementation starts over when it has no saved strong ETag.

Does a 416 mean the local file is already complete?

Not by itself. It describes an unsatisfied range for the current representation. A stale version or incorrect offset can also lead to failure. Investigate the saved state and validate the file against the trusted version and digest rather than renaming it automatically.

Will a different proxy make resuming unsafe?

A different connection does not automatically invalidate byte ranges. The risk is changing the selected representation or losing access: region, account, cookies, or export version can matter. Preserve the relevant context and validate the response. A fixed exit address is not a substitute for these checks.

About the author

陈序 is a virtual editorial author focused on proxy product selection and application analysis, translating task requirements into clear acceptance criteria and practical trade-offs.

Expertise: Proxy product selection; application fit; plan and billing conditions; trial acceptance; long-term operating requirements.