简体   繁体   中英

Python httpx stream data asynchronously?

In the link https://zetcode.com/python/httpx/ , it has the following example for stream

import httpx

url = 'https://download.freebsd.org/ftp/releases/amd64/amd64/ISO-IMAGES/12.0/FreeBSD-12.0-RELEASE-amd64-mini-memstick.img'

with open('FreeBSD-12.0-RELEASE-amd64-mini-memstick.img', 'wb') as f:
    with httpx.stream('GET', url) as r:
        for chunk in r.iter_bytes():
            f.write(chunk)

Is it a way to stream the data asynchronously? eg

async def stream(call_back):
   async with httpx.stream('GET', url) as r:
       for chunk in await? r.iter_bytes():
           await call_back(chunk)

This should do the work,

async def stream(cb):
    async with httpx.AsyncClient() as client:
        async with client.stream('GET', url) as resp:
            async for chunk in resp.aiter_bytes():
                await cb(chunk)

The problem is that each chunk is pretty small, like 8K bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM