How do use httpx with Django async view to stream response from remote server?
#2616
-
|
I am attempting to use Django to talk to my Remix server to stream a response. I cannot figure out what I am doing wrong when utilizing Django. If I adapt the use of Starlette to do it, it works perfectly. In Django (using 4.2b1 since async_client = httpx.AsyncClient()
...
async def get_streaming_data(url, headers):
async_request = httpx.Request(
"GET",
url,
headers=headers,
)
async_response = await async_client.send(
async_request, stream=True, follow_redirects=False
)
async def stream_content():
async for chunk in async_response.aiter_bytes():
yield chunk
response = StreamingHttpResponse(
stream_content(),
status=async_response.status_code,
content_type=async_response.headers.get("content-type"),
)
return responseand in my Class Based View I request a service that is running on my host from Docker container async def get(self, *args, **kwargs):
url = "http://host.docker.internal:3001/sandbox/testing-async/"
return await get_streaming_data(url, self.get_request_headers())Unfortunately with a streaming response I receive a If I do a request to an endpoint that delivers a small response, it works fine. What am I missing about the concept of how this is supposed to work when keeping a stream open? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
I have successfully resolved this. The issue was Middleware which wasn't handling the async properly. I had to subclass |
Beta Was this translation helpful? Give feedback.
I have successfully resolved this. The issue was Middleware which wasn't handling the async properly. I had to subclass
from django.utils.deprecation import MiddlewareMixin. I hope this can help someone else.