read a stream and respond to another user request
import requests
from 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) # stream set to True in order to only download headers without consuming response.body
response = StreamingHttpResponse(
(chunk for chunk in r.iter_content(512 * 1024)),
content_type='application/json')
return response
yield response
from django.views.decorators.http import condition
@condition(etag_func=None)
def stream_response(request):
resp = HttpResponse( stream_response_generator(), content_type='text/html')
return resp
def stream_response_generator():
yield "<html><body>\n"
for x in range(1,11):
yield "<div>%s</div>\n" % x
yield " " * 1024 # Encourage browser to render incrementally
time.sleep(1)
yield "</body></html>\n"
def chunked_res():
yield "Chunk 1"
yield " " * 1024 # Encourage browser to render incrementally (either 1024 or 1024-7{length of "chunk 1"} = 1017)
time.sleep(5) # wait for 5 seconds
yield "Chunk 2"
def myview(request):
g = chunked_res()
return HttpResponse(g)
build a response with BytesIO
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from django.http import HttpResponse
from xlsxwriter.workbook import Workbook
def your_view(request):
# your view logic here
# create a workbook in memory
output = StringIO.StringIO()
book = Workbook(output)
sheet = book.add_worksheet('test')
sheet.write(0, 0, 'Hello, world!')
book.close()
# construct response
output.seek(0)
response = HttpResponse(output.read(), mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=test.xlsx"
return response
build a response for a zip file
from io import BytesIO
mem_file = BytesIO()
with zipfile.ZipFile(mem_file, "w") as zip_file:
for i, planner in enumerate(planner_list):
file_name = str(planner[0].start_date)
content = render_to_string('deneme.html', {'schedule':schedule})
zip_file.writestr(file_name, content)
f.seek(0) # rewind file pointer just in case
response = HttpResponse(f, content_type='application/zip')
Was this article helpful?
This article is viewed 11 times!