title: Django 3.1: StreamingHttpResponse with an async generator
body: <p><a href="https://docs.djangoproject.com/en/3.1/topics/async/#async-views:%7E:text=The%20main%20benefits%20are%20the%20ability,long%2Dpolling%2C%20and%20other%20exciting%20response%20types." rel="noreferrer">Documentation for Django 3.1</a> says this about async views:</p>
  <blockquote>
  <p>The main benefits are the ability to service hundreds of connections without using Python threads. This allows you to use slow streaming, long-polling, and other exciting response types.</p>
  </blockquote>
  <p>I believe that &quot;slow streaming&quot; means we could implement an <a href="https://en.wikipedia.org/wiki/Server-sent_events" rel="noreferrer">SSE</a> view without monopolizing a thread per client, so I tried to sketch a simple view, like so:</p>
  <pre class="lang-py prettyprint-override"><code>async def stream(request):
  
      async def event_stream():
          while True:
              yield 'data: The server time is: %s\n\n' % datetime.datetime.now()
              await asyncio.sleep(1)
  
      return StreamingHttpResponse(event_stream(), content_type='text/event-stream')
  </code></pre>
  <p>(note: I adapted the code from <a href="https://stackoverflow.com/a/55522953/1164966">this response</a>)</p>
  <p>Unfortunately, when this view is invoked, it raises the following exception:</p>
  <pre><code>Traceback (most recent call last):
    File &quot;/usr/local/lib/python3.7/site-packages/asgiref/sync.py&quot;, line 330, in thread_handler
      raise exc_info[1]
    File &quot;/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py&quot;, line 38, in inner
      response = await get_response(request)
    File &quot;/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py&quot;, line 231, in _get_response_async
      response = await wrapped_callback(request, *callback_args, **callback_kwargs)
    File &quot;./chat/views.py&quot;, line 144, in watch
      return StreamingHttpResponse(event_stream(), content_type='text/event-stream')
    File &quot;/usr/local/lib/python3.7/site-packages/django/http/response.py&quot;, line 367, in __init__
      self.streaming_content = streaming_content
    File &quot;/usr/local/lib/python3.7/site-packages/django/http/response.py&quot;, line 382, in streaming_content
      self._set_streaming_content(value)
    File &quot;/usr/local/lib/python3.7/site-packages/django/http/response.py&quot;, line 386, in _set_streaming_content
      self._iterator = iter(value)
  TypeError: 'async_generator' object is not iterable
  </code></pre>
  <p>To me, this shows that <code>StreamingHttpResponse</code> doesn't currently support async generators.</p>
  <p>I tried to modify <code>StreamingHttpResponse</code> to use <code>async for</code> but I wasn't able to do much.</p>
  <p>Any idea how I could do that?</p>