Skip to content

Fix iter_lines boundary bug when CRLF straddles two chunks #4629

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions requests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,7 @@ def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=
"""

pending = None
carriage_return = u'\r' if decode_unicode else b'\r'

for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):

Expand All @@ -798,13 +799,17 @@ def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=

if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
pending = lines.pop()
elif not delimiter and lines and chunk.endswith(carriage_return):
pending = lines.pop() + carriage_return
else:
pending = None

for line in lines:
yield line

if pending is not None:
if not delimiter:
pending = pending.rstrip(carriage_return)
yield pending

@property
Expand Down
10 changes: 10 additions & 0 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""Tests for Requests."""

from __future__ import division
import base64
import json
import os
import pickle
Expand Down Expand Up @@ -1738,6 +1739,15 @@ def test_response_iter_lines(self, httpbin):
next(it)
assert len(list(it)) == 3

@pytest.mark.parametrize('chunk', (3, 4))
@pytest.mark.parametrize('decode', (True, False))
def test_response_iter_lines_crlf_across_chunks(self, httpbin, chunk, decode):
b64_body = base64.b64encode(b'one\r\ntwo\r\rthree\r').decode('ascii')
r = requests.get(httpbin('base64/' + b64_body), stream=True)

it = r.iter_lines(chunk_size=chunk, decode_unicode=decode)
assert [len(line) for line in it] == [3, 3, 0, 5]

def test_response_context_manager(self, httpbin):
with requests.get(httpbin('stream/4'), stream=True) as response:
assert isinstance(response, requests.Response)
Expand Down