Skip to content

Instantly share code, notes, and snippets.

@SidJain1412
Created May 11, 2023 11:20
Show Gist options
  • Save SidJain1412/ac7713d170372f5f25513ef58d4c6c24 to your computer and use it in GitHub Desktop.
Save SidJain1412/ac7713d170372f5f25513ef58d4c6c24 to your computer and use it in GitHub Desktop.
Calling a Streaming API using requests library in Python
import requests
url = "http://127.0.0.1:8000/campaign/?prompt=Pepsi"
response = requests.get(
url,
stream=True,
headers={"accept": "application/json"},
)
for chunk in response.iter_content(chunk_size=1024):
if chunk:
print(str(chunk, encoding="utf-8"), end="")
@shaojun
Copy link

shaojun commented Jul 17, 2024

I'm using the sample code which almost the same as yours:

import requests

def get_stream(url):
    s = requests.Session()

    with s.get(url, headers=None, stream=True) as resp:
        for line in resp.iter_lines():
            if line:
                print(line)

url = 'https://jsonplaceholder.typicode.com/posts/1'
get_stream(url)

it works, but how to check the stream status afterwards? I did a simple test, once the http client(above code) to server has build, I then killed the server, the client code will stuck at resp.iter_lines() forever

@SidJain1412
Copy link
Author

Once the streaming response ends it should end the for loop, is it happening for you that the code is stuck in the loop?

@shaojun
Copy link

shaojun commented Jul 17, 2024

just tried again, there's a timeout exception poped up when the stream does not have incoming data for a while.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment