【发布时间】:2016-11-25 16:14:55
【问题描述】:
如何使用 Django 从外部 API 获取由用户请求触发的数据,并在请求周期中直接将其流式传输回,而不使用(或渐进式/最小)内存使用?
背景
作为连接外部托管微服务的短期解决方案,需要将用户可访问性(基于 Django 应用程序的身份验证系统)限制为非身份验证 API。以前的开发人员在 Javascript 中公开了这些外部 IP,我们需要一个解决方案来让它们远离公众视线。
要求
- 我们不一定要使用 requests 库,如果它可以帮助加快响应时间,我们愿意使用任何其他库。
- 来自外部 API 的响应可能有点大 (5-10MB),并且能够缩短请求周期(通过 Ajax > Django > External API > Django > User 的用户请求)至关重要。
这可能吗?如果有,您能推荐一个方法吗?
from django.shortcuts import Http404, HttpResponse
import requests
def api_gateway_portal(request, path=''):
# Determine whether to grant access
# If so, fetch and return data
r = requests.get('http://some.ip.address/%s?api_key=12345678901234567890' % (path,))
# Return as JSON
response = HttpResponse(r.content, content_type='application/json')
response['Content-Length'] = len(r.content)
return response
请注意 - 我完全知道这是一个糟糕的长期解决方案,但在新的外部身份验证系统完成之前,出于演示目的,这是短期内必要的。
【问题讨论】:
标签: python django python-requests