{"id":"a3498989f4bc6eba","repo":"psf/requests","slug":"an-error-occurred-when-rewinding-request-body-for","errorCode":null,"errorMessage":"An error occurred when rewinding request body for redirect.","messagePattern":"An error occurred when rewinding request body for redirect\\.","errorType":"exception","errorClass":"UnrewindableBodyError","httpStatus":null,"severity":"error","filePath":"src/requests/utils.py","lineNumber":1151,"sourceCode":"\n    netloc = netloc.rsplit(\"@\", 1)[-1]\n\n    return urlunparse((scheme, netloc, path, params, query, \"\"))\n\n\ndef rewind_body(prepared_request: PreparedRequest) -> None:\n    \"\"\"Move file pointer back to its recorded starting position\n    so it can be read again on redirect.\n    \"\"\"\n    body_seek = getattr(prepared_request.body, \"seek\", None)\n    if body_seek is not None and isinstance(\n        prepared_request._body_position,\n        integer_types,\n    ):\n        try:\n            body_seek(prepared_request._body_position)\n        except OSError:\n            raise UnrewindableBodyError(\n                \"An error occurred when rewinding request body for redirect.\"\n            )\n    else:\n        raise UnrewindableBodyError(\"Unable to rewind request body for redirect.\")\n","sourceCodeStart":1133,"sourceCodeEnd":1156,"githubUrl":"https://github.com/psf/requests/blob/414f0513c33883adf6f2b46901d4f0b38a455851/src/requests/utils.py#L1133-L1156","documentation":"Raised as `requests.exceptions.UnrewindableBodyError` from `rewind_body()` in `src/requests/utils.py:1151`. When a server redirects a request that had a file-like body, requests must seek the body back to its recorded start position (`_body_position`) to resend it; the body object has a `seek()` method, but calling it raised OSError. The stream is therefore in an unknown position and the redirect cannot be safely followed.","triggerScenarios":"An upload (`requests.post(url, data=fileobj)` or `files=`) whose target responds with a 301/302/307/308 redirect, where the body's `seek()` exists but fails — e.g. a pipe, socket, or `sys.stdin.buffer` wrapped so seek raises, an HTTP response object used as a body (`data=other_resp.raw`), or a file whose underlying handle was closed/consumed.","commonSituations":"Streaming one HTTP response directly into another request; uploading from stdin or a subprocess pipe; endpoints that redirect POST/PUT (e.g. http→https redirect, trailing-slash redirect, S3 region redirect) while the body is a non-seekable stream.","solutions":["Send the request to the final URL directly so no redirect occurs (fix http→https, add the trailing slash, use the region-correct endpoint).","Buffer the body into memory or a real file first: `data=io.BytesIO(stream.read())`, which seeks reliably.","Disable redirects and handle them yourself: `resp = requests.post(url, data=stream, allow_redirects=False)`, then re-open the stream for the new location.","If seek fails because the file was closed, keep the file open for the duration of the request."],"exampleFix":"# before\nrequests.post('http://api.example.com/upload', data=sys.stdin.buffer)\n# after\nimport io\nbody = io.BytesIO(sys.stdin.buffer.read())\nrequests.post('https://api.example.com/upload', data=body)","handlingStrategy":"try-catch","validationCode":"# Ensure body is rewindable before sending: pass bytes/str, or a fresh seekable file\nbody = open(path, 'rb')  # seekable; avoid non-seekable streams (pipes, generators) with redirect-prone URLs","typeGuard":null,"tryCatchPattern":"try:\n    resp = requests.post(url, data=stream)\nexcept requests.exceptions.UnrewindableBodyError as e:\n    # seek() failed while replaying the body for a redirect\n    log.error('Body rewind failed on redirect: %s', e)\n    resp = requests.post(final_url, data=open(path, 'rb'), allow_redirects=False)","preventionTips":["Prefer in-memory bytes or seekable file objects over generators/pipes for request bodies","When streaming uploads, resolve the final URL first (allow_redirects=False, follow Location manually) so no rewind is needed","Reopen the source and retry against the redirect target if rewinding fails"],"tags":["redirect","upload","streaming","body-rewind","python","requests"],"analyzedSha":"414f0513c33883adf6f2b46901d4f0b38a455851","analyzedAt":"2026-07-31T19:24:57.696Z","schemaVersion":2}