Skip to content

Commit

Permalink
Merge pull request psf#3678 from nateprewitt/3675_streaming_docs
Browse files Browse the repository at this point in the history
decoding fix for Streaming Requests docs
  • Loading branch information
Lukasa authored Nov 14, 2016
2 parents 70f1f8e + d81ad06 commit 33bd38b
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions docs/user/advanced.rst
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,21 @@ set ``stream`` to ``True`` and iterate over the response with
for line in r.iter_lines():

# filter out keep-alive new lines
if line:
decoded_line = line.decode('utf-8')
print(json.loads(decoded_line))

When using `decode_unicode=True` with
:meth:`Response.iter_lines() <requests.Response.iter_lines>` or
:meth:`Response.iter_content() <requests.Response.iter_content>`, you'll want
to provide a fallback encoding in the event the server doesn't provide one::

r = requests.get('http://httpbin.org/stream/20', stream=True)

if r.encoding is None:
r.encoding = 'utf-8'

for line in r.iter_lines(decode_unicode=True):
if line:
print(json.loads(line))

Expand Down

0 comments on commit 33bd38b

Please sign in to comment.