uriyyo: @witling Also, it will be great to add tests to cover this feature.
witling: @uriyyo Thanks for the notes! I've updated my pull request.
witling: blocked by https://github.com/encode/starlette/pull/1040
witling: @JayH5 Thanks for your effort! I've updated my pr.
witling: annotations were implemented
witling: blocked by https://github.com/encode/starlette/pull/1072
diff --git a/starlette/responses.py b/starlette/responses.py
index 24e3b54..d5f2734 100644
--- a/starlette/responses.py
+++ b/starlette/responses.py
@@ -1,6 +1,5 @@
 import hashlib
 import http.cookies
-import inspect
 import json
 import os
 import stat
@@ -204,7 +203,7 @@ class StreamingResponse(Response):
         media_type: str = None,
         background: BackgroundTask = None,
     ) -> None:
-        if inspect.isasyncgen(content):
+        if isinstance(content, typing.AsyncIterable):
             self.body_iterator = content
         else:
             self.body_iterator = iterate_in_threadpool(content)

StreamingResponse doesn't support PEP-492 asynchronous iterators
[PEP-492 asynchronous iterators](https://www.python.org/dev/peps/pep-0492/#asynchronous-iterators-and-async-for) have the following signature:

```python
class AsyncIterable:
    def __aiter__(self):
        return self

    async def __anext__(self):
        data = await self.fetch_data()
        if data:
            return data
        else:
            raise StopAsyncIteration
```

For example, the Azure storage python library returns such an asynchronous iterator for blob downloading. I can't pass it to Starlette though; it will execute in the threadpool and crash there:

```
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/fastapi/applications.py", line 142, in __call__
    await super().__call__(scope, receive, send)  # pragma: no cover
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/starlette/applications.py", line 134, in __call__
    await self.error_middleware(scope, receive, send)
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/starlette/middleware/errors.py", line 178, in __call__
    raise exc from None
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/starlette/middleware/errors.py", line 156, in __call__
    await self.app(scope, receive, _send)
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/starlette/exceptions.py", line 73, in __call__
    raise exc from None
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/starlette/exceptions.py", line 62, in __call__
    await self.app(scope, receive, sender)
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/starlette/routing.py", line 590, in __call__
    await route(scope, receive, send)
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/starlette/routing.py", line 208, in __call__
    await self.app(scope, receive, send)
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/starlette/routing.py", line 44, in app
    await response(scope, receive, send)
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/starlette/responses.py", line 196, in __call__
    async for chunk in self.body_iterator:
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/starlette/concurrency.py", line 45, in iterate_in_threadpool
    yield await run_in_threadpool(_next, iterator)
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/starlette/concurrency.py", line 25, in run_in_threadpool
    return await loop.run_in_executor(None, func, *args)
  File "/home/korijn/.pyenv/versions/3.6.8/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/contextvars/__init__.py", line 38, in run
    return callable(*args, **kwargs)
  File "/home/korijn/.local/share/virtualenvs/aiotest--vQHOsY--/home/korijn/.pyenv/shims/python/lib/python3.6/site-packages/starlette/concurrency.py", line 37, in _next
    return next(iterator)
TypeError: '_AsyncChunkIterator' object is not an iterator
```

I have to wrap the iterator in an asynchronous generator function for it to work:

```
    async def chunks_generator():
        async for i in blob.chunks():
            yield i

    return StreamingResponse(chunks_generator())
```
diff --git a/tests/test_responses.py b/tests/test_responses.py
index a28bbbf..d1d26fc 100644
--- a/tests/test_responses.py
+++ b/tests/test_responses.py
@@ -101,6 +101,44 @@ def test_streaming_response():
     assert filled_by_bg_task == "6, 7, 8, 9"
 
 
+def test_streaming_response_custom_iterator():
+    async def app(scope, receive, send):
+        class CustomAsyncIterator:
+            def __init__(self):
+                self._called = 0
+
+            def __aiter__(self):
+                return self
+
+            async def __anext__(self):
+                if self._called == 5:
+                    raise StopAsyncIteration()
+                self._called += 1
+                return str(self._called)
+
+        response = StreamingResponse(CustomAsyncIterator(), media_type="text/plain")
+        await response(scope, receive, send)
+
+    client = TestClient(app)
+    response = client.get("/")
+    assert response.text == "12345"
+
+
+def test_streaming_response_custom_iterable():
+    async def app(scope, receive, send):
+        class CustomAsyncIterable:
+            async def __aiter__(self):
+                for i in range(5):
+                    yield str(i + 1)
+
+        response = StreamingResponse(CustomAsyncIterable(), media_type="text/plain")
+        await response(scope, receive, send)
+
+    client = TestClient(app)
+    response = client.get("/")
+    assert response.text == "12345"
+
+
 def test_sync_streaming_response():
     async def app(scope, receive, send):
         def numbers(minimum, maximum):

pip install -e .[full]
parse_log_pytest
requirements.txt
pytest
3.7
requirements.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
aiofiles==23.2.1
aiosqlite==0.19.0
appdirs==1.4.4
autoflake==2.1.1
Babel==2.14.0
black==20.8b1
bleach==6.0.0
certifi @ file:///croot/certifi_1671487769961/work/certifi
cffi==1.15.1
charset-normalizer==3.4.1
click==8.1.8
colorama==0.4.6
coverage==7.2.7
cryptography==44.0.2
databases==0.8.0
docutils==0.20.1
exceptiongroup==1.2.2
flake8==2.3.0
ghp-import==2.1.0
graphene==3.4.3
graphql-core==3.2.6
graphql-relay==3.2.0
greenlet==3.1.1
idna==3.10
importlib-metadata==6.7.0
importlib-resources==5.12.0
iniconfig==2.0.0
isort==5.11.5
itsdangerous==2.1.2
jaraco.classes==3.2.3
jeepney==0.9.0
Jinja2==3.1.6
keyring==24.1.1
Markdown==3.4.4
markdown-it-py==2.2.0
MarkupSafe==2.1.5
mccabe==0.7.0
mdurl==0.1.2
mergedeep==1.3.4
mkautodoc==0.2.0
mkdocs==1.5.3
mkdocs-material==9.2.7
mkdocs-material-extensions==1.2
more-itertools==9.1.0
mypy==1.4.1
mypy-extensions==1.0.0
packaging==24.0
paginate==0.5.7
pathspec==0.11.2
pep8==1.7.1
pkginfo==1.10.0
platformdirs==4.0.0
pluggy==1.2.0
pycparser==2.21
pyflakes==3.0.1
Pygments==2.17.2
pymdown-extensions==10.2.1
pytest==7.4.4
pytest-asyncio==0.21.2
pytest-cov==4.1.0
python-dateutil==2.9.0.post0
python-multipart==0.0.8
pytz==2025.2
PyYAML==6.0.1
pyyaml_env_tag==0.1
readme-renderer==37.3
regex==2022.10.31
requests==2.31.0
requests-toolbelt==1.0.0
rfc3986==2.0.0
rich==13.8.1
SecretStorage==3.3.3
six==1.17.0
SQLAlchemy==1.4.54
-e git+https://github.com/encode/starlette.git@c300bdc5b88f6e3c4467f361c82e3445811cc70f#egg=starlette
toml==0.10.2
tomli==2.0.1
twine==4.0.2
typed-ast==1.5.5
typing_extensions==4.7.1
ujson==5.7.0
urllib3==2.0.7
watchdog==3.0.0
webencodings==0.5.1
zipp==3.15.0

name: starlette
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2022.12.7=py37h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.4.4=h6a678d5_1
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - pip=22.3.1=py37h06a4308_0
  - python=3.7.16=h7a1cb2a_0
  - readline=8.2=h5eee18b_0
  - setuptools=65.6.3=py37h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - wheel=0.38.4=py37h06a4308_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - aiofiles==23.2.1
      - aiosqlite==0.19.0
      - appdirs==1.4.4
      - autoflake==2.1.1
      - babel==2.14.0
      - black==20.8b1
      - bleach==6.0.0
      - cffi==1.15.1
      - charset-normalizer==3.4.1
      - click==8.1.8
      - colorama==0.4.6
      - coverage==7.2.7
      - cryptography==44.0.2
      - databases==0.8.0
      - docutils==0.20.1
      - exceptiongroup==1.2.2
      - flake8==2.3.0
      - ghp-import==2.1.0
      - graphene==3.4.3
      - graphql-core==3.2.6
      - graphql-relay==3.2.0
      - greenlet==3.1.1
      - idna==3.10
      - importlib-metadata==6.7.0
      - importlib-resources==5.12.0
      - iniconfig==2.0.0
      - isort==5.11.5
      - itsdangerous==2.1.2
      - jaraco-classes==3.2.3
      - jeepney==0.9.0
      - jinja2==3.1.6
      - keyring==24.1.1
      - markdown==3.4.4
      - markdown-it-py==2.2.0
      - markupsafe==2.1.5
      - mccabe==0.7.0
      - mdurl==0.1.2
      - mergedeep==1.3.4
      - mkautodoc==0.2.0
      - mkdocs==1.5.3
      - mkdocs-material==9.2.7
      - mkdocs-material-extensions==1.2
      - more-itertools==9.1.0
      - mypy==1.4.1
      - mypy-extensions==1.0.0
      - packaging==24.0
      - paginate==0.5.7
      - pathspec==0.11.2
      - pep8==1.7.1
      - pkginfo==1.10.0
      - platformdirs==4.0.0
      - pluggy==1.2.0
      - pycparser==2.21
      - pyflakes==3.0.1
      - pygments==2.17.2
      - pymdown-extensions==10.2.1
      - pytest==7.4.4
      - pytest-asyncio==0.21.2
      - pytest-cov==4.1.0
      - python-dateutil==2.9.0.post0
      - python-multipart==0.0.8
      - pytz==2025.2
      - pyyaml==6.0.1
      - pyyaml-env-tag==0.1
      - readme-renderer==37.3
      - regex==2022.10.31
      - requests==2.31.0
      - requests-toolbelt==1.0.0
      - rfc3986==2.0.0
      - rich==13.8.1
      - secretstorage==3.3.3
      - six==1.17.0
      - sqlalchemy==1.4.54
      - toml==0.10.2
      - tomli==2.0.1
      - twine==4.0.2
      - typed-ast==1.5.5
      - typing-extensions==4.7.1
      - ujson==5.7.0
      - urllib3==2.0.7
      - watchdog==3.0.0
      - webencodings==0.5.1
      - zipp==3.15.0
prefix: /opt/conda/envs/starlette

tests/test_responses.py::test_streaming_response_custom_iterator tests/test_responses.py::test_streaming_response_custom_iterable
tests/test_responses.py::test_head_method
tests/test_responses.py::test_text_response tests/test_responses.py::test_bytes_response tests/test_responses.py::test_ujson_response tests/test_responses.py::test_json_none_response tests/test_responses.py::test_redirect_response tests/test_responses.py::test_streaming_response tests/test_responses.py::test_sync_streaming_response tests/test_responses.py::test_response_headers tests/test_responses.py::test_response_phrase tests/test_responses.py::test_file_response tests/test_responses.py::test_file_response_with_directory_raises_error tests/test_responses.py::test_file_response_with_missing_file_raises_error tests/test_responses.py::test_file_response_with_chinese_filename tests/test_responses.py::test_set_cookie tests/test_responses.py::test_delete_cookie tests/test_responses.py::test_populate_headers
starlette/responses.py
starlette/responses.py