[Python] How to read lines of a streaming api with aiohttp in Python?

Discussão em 'Python' iniciado por Stack, Maio 4, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to convert a Python HTTP client featuring requests to aiohttp. The logic is to send a GET call to a REST endpoint which streams data occasionally and print the lines it returns.

    I have a code using requests with stream=True option and iter_lines, it works pretty fine:

    import json
    import requests

    def main():
    with requests.get('https://my-streaming-url.com', stream=True) as r:
    if r.encoding is None:
    r.encoding = 'utf-8'
    for line in r.iter_lines(decode_unicode=True):
    if line:
    # Print each line emitted by the streaming api
    print(json.loads(line))

    if __name__ == '__main__':
    main()


    Now, I want to convert this logic to aiohttp streaming api and tried:

    import asyncio
    import aiohttp
    import json

    loop = asyncio.get_event_loop()

    async def main():
    r = aiohttp.request('get', 'https://my-streaming-url.com')
    async for line in r.content:
    print(json.loads(line))

    if __name__ == '__main__':
    loop.run_until_complete(connect_and_listen())
    loop.close()


    I get an error like:


    ... in connect_and_listen

    async for line in r.content:

    AttributeError: '_SessionRequestContextManager' object has no attribute 'content'

    sys:1: RuntimeWarning: coroutine 'ClientSession._request' was never awaited

    Unclosed client session

    client_session: aiohttp.client.ClientSession object at 0x7fac6ec24310
    ​

    I tried a few ways like removing loop.close() from main, removing async from the for loop, but none helped.

    What am I missing here? How can I print a streaming api lines with aiohttp?

    P.S: My Python version is 3.7.5

    Continue reading...

Compartilhe esta Página