Python UnicodeDecodeError:'ascii'编解码器无法解码位置12中的字节0xd0:序数不在范围内(128)

时间:2017-06-16 09:17:15

标签: python django django-rest-framework

我正在尝试使用Django rest框架从基于类的视图返回StreamingHttpResponse中的文件。但是,我得到一个非常神秘的错误消息,其堆栈跟踪不包含对我的代码的任何引用:

16/Jun/2017 11:08:48] "GET /api/v1/models/49 HTTP/1.1" 200 0
Traceback (most recent call last):
  File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 138, in run
    self.finish_response()
  File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 179, in finish_response
    for data in self.result:
  File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/util.py", line 30, in __next__
    data = self.filelike.read(self.blksize)
  File "/Users/jonathan/anaconda/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 12: ordinal not in range(128)

[...]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 141, in run
    self.handle_error()
  File "/Users/jonathan/anaconda/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 88, in handle_error
    super(ServerHandler, self).handle_error()
  File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 368, in handle_error
    self.finish_response()
  File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 180, in finish_response
    self.write(data)
  File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 274, in write
    self.send_headers()
  File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 331, in send_headers
    if not self.origin_server or self.client_is_modern():
  File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 344, in client_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable

我的get方法如下所示:

def get(self, request, pk, format=None):
    """
    Get model by primary key (pk)
    """
    try:
        model = QSARModel.objects.get(pk=pk)
    except Exception:
        raise Http404
    filename = model.pluginFileName
    chunk_size = 8192
    response = StreamingHttpResponse(
                   FileWrapper( open(filename), chunk_size ),
                   content_type = 'application/zip' )
    return response

从谷歌搜索我觉得这与ASCII / UTF8编码有关,但我不明白这是如何适用于我的情况。我正在处理二进制文件。实际上它是一个Java jar文件但据我所知,它应该是一个zip文件。这里发生了什么,我做错了什么?

1 个答案:

答案 0 :(得分:0)

这与语言翻译有关。当使用django存储系统的非ascii文件名时。所以在apache envvars中添加以下行

export LANG='en_US.UTF-8'
export LC_ALL='en_US.UTF-8'

https://code.djangoproject.com/wiki/django_apache_and_mod_wsgi#AdditionalTweaking