Streaming Requests

With requests.Response.iter_lines() you can easily iterate over streaming APIs such as the Twitter Streaming API. Simply set stream to True and iterate over the response with iter_lines():

  1. import json
  2. import requests
  3. r = requests.get('http://httpbin.org/stream/20', stream=True)
  4. for line in r.iter_lines():
  5. # filter out keep-alive new lines
  6. if line:
  7. print(json.loads(line))

Warning

iter_lines() is not reentrant safe. Calling this method multiple times causes some of the received data being lost. In case you need to call it from multiple places, use the resulting iterator object instead:

  1. lines = r.iter_lines()
  2. # Save the first line for later or just skip it
  3. first_line = next(lines)
  4. for line in lines:
  5. print(line)