how can django used fetch data external api, triggered user request, , stream directly in request cycle without (or progressive/minimal) memory usage?
background
as short-term solution connect externally hosted micro-services, there need limit user accessibility (based off django application's authentication system) non-authenticated api. previous developers exposed these external ips in javascript , need solution them out of public eye.
requirements
- we not bound using requests library , open using others if can speed response time.
- responses external api may large (5-10mb) , being able shorten request cycle (user request via ajax > django > external api > django > user) crucial.
is possible? if so, can suggest method?
from django.shortcuts import http404, httpresponse import requests def api_gateway_portal(request, path=''): # determine whether grant access # if so, fetch , return data r = requests.get('http://some.ip.address/%s?api_key=12345678901234567890' % (path,)) # return json response = httpresponse(r.content, content_type='application/json') response['content-length'] = len(r.content) return response
please note - aware poor long-term solution, necessary short-term demo purposes until new external authentication system completed.
import requests django.http import streaminghttpresponse def api_gateway_portal(request, path=''): url = 'http://some.ip.address/%s?api_key=12345678901234567890' % (path,) r = requests.get(url, stream=true) response = streaminghttpresponse( (chunk chunk in r.iter_content(512 * 1024)), content_type='application/json') return response
documentation:
- body content workflow (
stream=true
explained) streaminghttpresponse
iter_content()
Comments
Post a Comment