Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Please support async generators #5

Open
keit0728 opened this issue Jul 22, 2024 · 0 comments
Open

Please support async generators #5

keit0728 opened this issue Jul 22, 2024 · 0 comments

Comments

@keit0728
Copy link

keit0728 commented Jul 22, 2024

If you try to fetch a file asynchronously and derive the cid as shown below, you will get an error saying object async_generator can't be used in 'await' expression.

import httpx
from ipfs_cid import cid_sha256_hash_chunked

async def write_chunks(url: str) -> Iterable[bytes]:
    async with httpx.AsyncClient() as client:
        async with client.stream("GET", url) as res:
            async for chunk in res.aiter_bytes():
                yield chunk

cid = cid_sha256_hash_chunked(
    await write_chunks(url="https://example.com")
)

I can avoid the above error by implementing it as shown below using cid_sha256_wrap_digest.

import httpx
from ipfs_cid import cid_sha256_wrap_digest

async def write_chunks(url: str) -> Iterable[bytes]:
    async with httpx.AsyncClient() as client:
        async with client.stream("GET", url) as res:
            async for chunk in res.aiter_bytes():
                yield chunk

async def cid_sha256_hash_async_chunked(
    data: Iterable[bytes],
) -> str:
    sha = sha256()
    async for chunk in data:
        sha.update(chunk)
    return cid_sha256_wrap_digest(sha.digest())

cid = await cid_sha256_hash_async_chunked(
    write_chunks(url="https://example.com")
)

While the above implementation works, it would be very helpful if you could implement a version of cid_sha256_hash_chunked that supports async generators (like the above cid_sha256_hash_async_chunked) in the library, so that we can use it without needing to extend it ourselves. 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant