【问题标题】:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 14: invalid start byteUnicodeDecodeError:“utf-8”编解码器无法解码位置 14 中的字节 0xb9:无效的起始字节
【发布时间】:2018-03-11 11:04:39
【问题描述】:

我正在使用 Django REST 进行文件上传测试。
Python3.6.2
Django1.11
djangorestframework==3.6.4
Excel-OSX 15.38(170902)
OSX 10.12.6

以前用普通的照片文件就可以成功。
这次是来自网站的 Excel 文件。这是我的参考文献中的测试用例副本。

 def test_upload_and_process_data_complete_case(self):
        from django.core.files import File
        from django.core.files.uploadedfile import SimpleUploadedFile
        from soken_web.apps.imported_files.models import ImportFile

        file = File(open(str(settings.BASE_DIR) + '/apps/zipcodes/complete.xlsx'))
        uploaded_file = SimpleUploadedFile('new_image.xlsx', file.read(), content_type='multipart/form-data')

        data = {
            'attribute': {'author': 'Sigh'},
            'type': ImportFile.FileType.zipcode,
            'file': uploaded_file
        }
        response = self.client.post(reverse('api:import_file-list'), data, format='multipart')
        response.render()

        self.assertEqual(status.HTTP_201_CREATED, response.status_code)

就像一只模仿猫。除了这次我从https://www.mockaroo.com/ 下载一个模拟文件。

这是我执行file.read()时引发的错误

file
<File: /Users/el/Code/norak-cutter/soken/soken-web/soken_web/apps/zipcodes/complete.xlsx>
file.read()
Traceback (most recent call last):
  File "/Users/el/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/172.3968.37/PyCharm.app/Contents/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec
    exec(exp, global_vars, local_vars)
  File "<input>", line 1, in <module>
  File "/Users/el/.pyenv/versions/3.6.2/lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 14: invalid start byte

确认:
1. 我可以从我的网络浏览器上传文件
2. 我可以在没有任何警告消息的情况下打开该文件。

问题:
有什么我忘记关心的吗?

参考资料:
How can I test binary file uploading with django-rest-framework's test client?
Django REST UnitTest No file was submitted

【问题讨论】:

    标签: python django excel macos


    【解决方案1】:

    打开文件的默认模式是“r”,表示非二进制读取。 Python 假设您的文件是文本(编码)文件并尝试解码内容。但它不是文本文件 - 它是二进制数据文件。

    变化:

    open(str(settings.BASE_DIR) + '/apps/zipcodes/complete.xlsx')
    

    到:

    open(str(settings.BASE_DIR) + '/apps/zipcodes/complete.xlsx', 'rb')
    

    它可能会起作用。

    【讨论】:

    • AssertionError:测试数据包含键“属性”的字典值,但分段上传不支持嵌套数据。您可能需要考虑在此测试用例中使用 format='json'。
    • 那是一个不同的问题......因为我觉得我很慈善,你应该看看stackoverflow.com/a/11170472/2372812
    • 我曾尝试在 OSX 上复制里面的内容并用我的 Excel 粘贴。我得到了不同的号码而不是 0xb90x8e....
    • 您现在似乎遇到了不同的问题。感谢您接受我的回答并为您的新问题提出一个新问题:)
    • 非常感谢您的努力。但如果我接受你的回答。我下一个问题的问题是什么?它将被复制一个。
    猜你喜欢
    • 2021-02-07
    • 2022-05-30
    • 2021-12-01
    • 2016-05-13
    • 2017-05-03
    • 2020-02-06
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多