Python请求从streaminghttpresponse获取内容

2024-04-24 13:15:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个DjangoAPI,它使用protobuff消息流式传输响应

def retrieve(self, request, event_date=None, notification=None):
   ...
   return StreamingHttpResponse(self.generator(leaseEvents, 2000), content_type='application/protobuf')

def generator(self, qs, BATCH_SIZE=2000):
    pages = Paginator(qs.order_by("event_date").values_list('reference', 'event_date', 'event_msg'), BATCH_SIZE)
    for i in pages.page_range:
        p = pages.get_page(i)
        for event in p:
            # filling protobuf object
            yield lease_event.SerializeToString()


使用Postman查询API效果很好

我的目标是使用python请求模块获得结果,但我只得到一个空响应

with requests.get(url, stream=True) as r:
    print(r)
    print(r.headers.get('content-type'))
    print(r.headers)
    print(r.content)
    print(len(r.content))
    print(r.elapsed.total_seconds())
    for line in r.iter_lines():
        print("hi")
        if line:  # filter out keep-alive new lines
            print(line)

结果如下

<Response [200]>
application/protobuf
{'Date': 'Tue, 14 Apr 2020 09:05:45 GMT', 'Server': 'WSGIServer/0.2 CPython/3.8.1', 'Content-Type': 'application/protobuf', 'Vary': 'Accept, Cookie', 'Allow': 'GET, HEAD, OPTIONS', 'X-Frame-Options': 'SAMEORIG
IN', 'Content-Length': '0'}
b''
0
0.675784

我认为请求假定content-length为0,即使我使用的StreamingHttpResponse不提供content-length

我错过什么了吗

提前感谢:)


Tags: inselfnoneeventforgetdateapplication