django return file over HttpResponse - file is not served correctly

后端 未结 3 474
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 07:40

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

相关标签:
3条回答
  • 2020-12-29 08:05

    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")
    
    0 讨论(0)
  • 2020-12-29 08:17

    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.

    0 讨论(0)
  • 2020-12-29 08:26

    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.

    0 讨论(0)
提交回复
热议问题