小编Fel*_*oni的帖子

Iterable对象和Django StreamingHttpResponse

我想用django连接到内部http服务,我需要缓冲输出这些服务的http响应,因为一些内容非常大.

我使用的是python 3.6,django 2.0 http.client和以下代码:

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'] …
Run Code Online (Sandbox Code Playgroud)

python django python-3.x django-2.0

6
推荐指数
1
解决办法
626
查看次数

标签 统计

django ×1

django-2.0 ×1

python ×1

python-3.x ×1