简体   繁体   English

RESTful API的Django Streaming HTTP响应

[英]Django Streaming HTTP Response from RESTful API

I have a Django app that needs to interact with a database of medical images. 我有一个Django应用程序,需要与医学图像数据库进行交互。 They have a RESTful API that returns a stream of bytes, which I am writing to a HttpStreamingResponse . 他们有一个RESTful API,它返回字节流,我正在将它们写入HttpStreamingResponse This is working, but the issue is that it is very slow. 这是可行的,但问题是它非常慢。 Most files I am downloading are around 100mb, and it usually takes around 15-20 seconds before the download even begins. 我正在下载的大多数文件都在100mb左右,通常甚至需要15到20秒才能开始下载。 Does anyone have insight into how to speed up this process and start the download faster? 有谁知道如何加快此过程并更快地开始下载?

Here is my code: 这是我的代码:

# Make api call
response = requests.get(url, cookies=dict(JSESSIONID=self.session_id))
# write bytes to Http Response 
http = StreamingHttpResponse(io.BytesIO(response.content), content_type='application/zip')

http['Content-Disposition'] = 'attachment; filename="%s.zip"' % patient_id
return http

You are downloading the full response to your server before passing on the information. 您正在传递完整的响应到您的服务器,然后再传递信息。

You should just forward the response from the API call using the following: 您应该使用以下命令转发来自API调用的响应:

res = FROM API CALL
response = HttpResponse(ContentFile(res.content), 'application/zip')
response['Content-Disposition'] = 'attachment; filename={}.zip'.format(patient_id)
response['Content-Length'] = res.headers.get('Content-Length')
response['Content-Transfer-Encoding'] = res.headers.get('Content-Transfer-Encoding')
response['Content-Type'] = res.headers.get('Content-Type')
return response

Make sure you copy over any important headers. 确保复制所有重要的标题。


Edit: Since this is the only proposed solution, I'm editing to include the solution from John's comment in a more readable format: 编辑:由于这是唯一提出的解决方案,因此我正在编辑,以一种更具可读性的格式包括John的评论中的解决方案:

# Make api call 
response = requests.get(url, cookies=dict(JSESSIONID=self.session_id), stream=True) 
# write bytes to Http Response 
http = StreamingHttpResponse(response.iter_content(8096), content_type='application/zip') 
http['Content-Disposition'] = 'attachment; filename="%s.zip"' % patient_id 
return http

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM