Iterable Object and Django StreamingHttpResponse

I want to connect to internal http services using django, and I need to buffer the HTTP response output of these services because some content is very large.

I am using python 3.6, django 2.0, http.clientand the following code:

class HTTPStreamIterAndClose():
    def __init__(self, conn, res, buffsize):
        self.conn = conn
        self.res = res
        self.buffsize = buffsize
        self.length = 1

        bytes_length = int(res.getheader('Content-Length'))

        if buffsize < bytes_length:
            self.length = math.ceil(bytes_length/buffsize)

    def __iter__(self):
        return self

    def __next__(self):
        buff = self.res.read(self.buffsize)

        if buff is b'':
            self.res.close()
            self.conn.close()

            raise StopIteration
        else:

            return buff

    def __len__(self):
        return self.length


def passthru_http_service(request, server, timeout, path):
    serv = HTTPService(server, timeout)
    res = serv.request(path)

    response = StreamingHttpResponse(
        HTTPStreamIterAndClose(serv.connection, res, 200),
        content_type='application/json'
    )
    response['Content-Length'] = res.getheader('Content-Length')

    return response

And the answer is empty, I am testing an iterator with:

b''.join(HTTPStreamIterAndClose(serv.connection, res, 200)

And everything works fine, I don’t know why it doesn’t work.

+6
source share
2 answers

https://andrewbrookins.com/django/how-does-djangos-streaminghttpresponse-work-exactly/

First, some conditions must be true:

  • Customer must speak HTTP/1.1or newer
  • The request method was not HEAD
  • Content-Length
  • 204 304

, Gunicorn Transfer-Encoding: chunked , , .

, Gunicorn Transfer-Encoding: chunked, HttpResponse, !

, , , iterable .

, : Content-Length.

, Range.

+4

, , HTTP- ms, , - , , , , =/.

.

0

All Articles