Django: Fileresponse works fine in local but it doesnt in deployment
In local i did this
@login_required
@permission_required('plataforma.ADMIN', raise_exception=True)
def admin_descargar_planilla(request,plantilla_id):
try:
plantilla = Plantilla.objects.get(pk=plantilla_id)
except:
return render(request, "plataforma/error.html",{"tipo_error":"No se puede realizar esta accion ya que la plantilla ya no existe"})
buffer = util.crear_pdf(plantilla)
return FileResponse(buffer, content_type='application/pdf', filename=(plantilla.eett.username+" ("+str(plantilla.fecha)+")"))
The function crear_pdf returns an io.BytesIO(). When I try to use this views in production I recieve an Internal Server error (500) from the server instead of an django error. In the deployment I'm using openlitespeed. Also I try using an existing pdf instead of a buffer but its worst because i receive error 404 saying the url doesnt exist when it exist (this also works fine in local)
I recently had a similar issue to yours. The reason why you get an Internal Server error (500) is because you are loading the entire file into memory. It can quickly lead to high memory usage and potentially exhaust the available memory resources. So the solution is to transfer the file in small chunks and the function FileWrapper
helps with that.
from django.core.servers.basehttp import FileWrapper
@login_required
@permission_required('plataforma.ADMIN', raise_exception=True)
def admin_descargar_planilla(request,plantilla_id):
try:
plantilla = Plantilla.objects.get(pk=plantilla_id)
except:
return render(request, "plataforma/error.html",{"tipo_error":"No se puede realizar esta accion ya que la plantilla ya no existe"})
buffer = util.crear_pdf(plantilla)
wrapper = FileWrapper(buffer)
response = FileResponse(wrapper, content_type='application/pdf', filename=(plantilla.eett.username+" ("+str(plantilla.fecha)+")"))
response['Content-Disposition'] = 'attachment; filename=test.pdf'
response['Content-Length'] = buffer.tell()
buffer.seek(0) # Not sure if its required for your case but see how it works.
return response
Hope this helps.