I want to return some files in a HttpResponse and I\'m using the following function. The file that is returned always has a filesize of 1kb and I do not know why. I can open
Could it be that the file contains some non-ascii characters that render ok in production but not in development?
Try reading the file as binary:
fsock = open(file_path,"rb")
Try disabling "django.middleware.gzip.GZipMiddleware" from your MIDDLEWARE_CLASSES in settings.py
I had the same problem, and after I looked around the middleware folder, this middleware seemed guilty to me and removing it did the trick for me.
Try passing the fsock
iterator as a parameter to HttpResponse()
, rather than to its write()
method which I think expects a string.
response = HttpResponse(fsock, mimetype=...)
See http://docs.djangoproject.com/en/dev/ref/request-response/#passing-iterators
Also, I'm not sure you want to call close
on your file before returning response
. Having played around with this in the shell (I've not tried this in an actual Django view), it seems that the response
doesn't access the file until the response
itself is read. Trying to read a HttpResponse
created using a file that is now closed results in a ValueError: I/O operation on closed file
.
So, you might want to leave fsock
open, and let the garbage collector deal with it after the response is read.