question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

iter_content with chunk_size=None hangs when used with requests.Session on Python 3

See original GitHub issue

Under some specific circumstances, a loop using iter_content ends up hanging after all the content has been iterated over. Specifically, all the following conditions must be met for this to occur:

  • You must be using Python 3 (I’ve tested using 2.7.11 (under which this works) and 3.3.6, 3.4.11 and 3.5.1 (under which this bug occurs).
  • Use requests.Session(), not requests.
  • Set chunk_size=None in iter_content.

Here, have an example:

# requests_bug.py
import requests

def iterate_through_streamed_content(requests_module_or_session, chunk_size):
    r = requests_module_or_session.get('http://example.org', stream=True)
    r.raise_for_status()
    for chunk in r.iter_content(chunk_size=chunk_size):
        print(len(chunk))


iterate_through_streamed_content(requests, 1024)
print('requests, 1024 works')

iterate_through_streamed_content(requests, None)
print('requests, None works')

iterate_through_streamed_content(requests.Session(), 1024)
print('requests.Session(), 1024 works')

iterate_through_streamed_content(requests.Session(), None)
print('requests.Session(), None works')

print("That's all.")

Output 1 (bug does not occur in Python2.7):

$ python --version
Python 2.7.11
$ pip install -U requests
Requirement already up-to-date: requests in /home/...
$ python requests_bug.py 
1270
requests, 1024 works
1270
requests, None works
1270
requests.Session(), 1024 works
1270
requests.Session(), None works
That's all.

Output 2 (bug occurs in Python3.5):

$ python --version
Python 3.5.1
$ pip install -U requests
Requirement already up-to-date: requests in /home/...
$ python requests_bug.py 
1270
requests, 1024 works
1270
requests, None works
1270
requests.Session(), 1024 works
1270

…after which the script hangs until you do Ctrl+C.

This is all done on Ubuntu 16.04, using pyenv and its virtualenv feature for testing using different Python versions. (Thank you all for requests, btw! Keep on rocking 👍 )

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:13 (12 by maintainers)

github_iconTop GitHub Comments

1reaction
nateprewittcommented, Jul 17, 2016

Sounds good, will do.

0reactions
Lukasacommented, Jul 17, 2016

Ok, for now let’s close this. @nateprewitt, can you open an equivalent issue on the urllib3 repository? You can use this test code as the example (it should live in test_socketlevel.py in the urllib3 repo):

class TestStream(SocketDummyServerTestCase):
    def test_stream_none_unchunked_response_does_not_hang(self):
        done_event = Event()

        def socket_handler(listener):
            sock = listener.accept()[0]

            buf = b''
            while not buf.endswith(b'\r\n\r\n'):
                buf += sock.recv(65536)

            sock.send(
                b'HTTP/1.1 200 OK\r\n'
                b'Content-Length: 12\r\n'
                b'Content-type: text/plain\r\n'
                b'\r\n'
                b'hello, world'
            )
            done_event.wait(5)
            sock.close()

        self._start_server(socket_handler)
        pool = HTTPConnectionPool(self.host, self.port, retries=False)
        r = pool.request('GET', '/', timeout=1, preload_content=False)

        # Stream should read to the end.
        self.assertEqual([b'hello, world'], list(r.stream(None)))

        done_event.set()
Read more comments on GitHub >

github_iconTop Results From Across the Web

iter_content with chunk_size=None hangs when used with ...
iter_content with chunk_size=None hangs when used with requests.Session on Python 3 #3421. Closed. tobinus opened this issue on Jul 17, ...
Read more >
Python 3.6.5: Requests with streaming getting stuck in ...
It seems like if there is any interruption to the network during the download, the stream hangs up, and the connection goes dead....
Read more >
Advanced Usage — Requests 2.28.1 documentation
Sessions can also be used to provide default data to the request methods. ... If chardet is installed, requests uses it, however for...
Read more >
response.iter_content() - Python requests - GeeksforGeeks
Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used...
Read more >
requests 2.7.0 - PyPI
Python HTTP for Humans. ... Fix crash with custom method parameter to Session.request (#2317) ... Support for bytestring URLs on Python 3.x (#2238)....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found