django return file over HttpResponse - file is not served correctly

无人久伴 提交于 2019-11-30 08:29:54

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!