【发布时间】:2018-06-09 10:43:09
【问题描述】:
我想用 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'] = res.getheader('Content-Length')
return response
并且响应为空,我测试迭代器:
b''.join(HTTPStreamIterAndClose(serv.connection, res, 200)
一切正常,我不知道为什么不工作。
【问题讨论】:
-
浏览器控制台有错误吗?
-
不,没有错误
-
“不工作”是什么意思?你得到http 500吗? 200 有空白输出?请在您的问题中提供
curl -v http://localhost:8000/x/y/(或邮递员或...)输出。 -
正如我所说,空响应,什么都没有 =(
-
使用外部连接作为客户端,你会看到真正的“发生了什么”!根据您的问题,以这种方式连接到环回地址是不可能的(为流作业定义另一个环回)。
标签: python django python-3.x django-2.0