python - 使用 Python 3 的 Django SimpleUploadedFile

标签 python django python-3.x

有没有人有在 Python 3 中使用 Django 的 SimpleUploadedFile 的工作示例?

此代码在 Python 2 中有效,但在 Python 3 中无效。

我有以下测试:

测试.py

class AttachmentModelTests(TestCase):

    def setUp(self):
        self.model = mommy.make(LocationLevel)

        base_dir = dirname(dirname(dirname(__file__)))
        self.image = join(base_dir, "source/attachments/test_in/test-mountains.jpg")

    def test_create(self):
        _file = SimpleUploadedFile(self.image, "file_content",
            content_type="image/jpeg")
        attachment = Attachment.objects.create(
            model_id=self.model.id,
            file=_file
        )

        self.assertIsInstance(attachment, Attachment)
        self.assertEqual(
            attachment.filename,
            self.image.split('/')[-1] # test-mountains.jpg
        )

这是它输出的错误:

Traceback (most recent call last):
  File "/Users/alelevier/Documents/bsrs/bsrs-django/bigsky/generic/tests/test_models.py", line 97, in test_create
    content_type="image/jpeg")
  File "/Users/alelevier/.virtualenvs/bs/lib/python3.4/site-packages/django/core/files/uploadedfile.py", line 114, in __init__
    super(SimpleUploadedFile, self).__init__(BytesIO(content), None, name,
TypeError: 'str' does not support the buffer interface

最佳答案

SO answer帮我解决了。

最后,这是更新后的工作测试代码:

def test_create(self):
    (abs_dir_path, filename) = os.path.split(self.image)

    with open(self.image) as infile:
        _file = SimpleUploadedFile(filename, infile.read())
        attachment = Attachment.objects.create(
            model_id=self.model.id,
            file=_file
        )

        self.assertIsInstance(attachment, Attachment)
        self.assertEqual(
            attachment.filename,
            self.image.split('/')[-1] # test-mountains.jpg
        )

关于python - 使用 Python 3 的 Django SimpleUploadedFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33173857/

相关文章:

mysql - Django:创建索引:非唯一,多列

python - 装饰方法(类方法重载)

python - 将变量值插入字符串

Python 列表过滤 : remove subsets from list of lists

python - 向 django 查询添加虚拟字段

c# - PHP/Rails/Django/ASP 网站应该是用 C++ 写的吧?

python - 在 Apache Airflow 的自定义运算符中访问 params 参数

python - asyncio 无法在 Windows 上读取标准输入

python - NumPy 的 : calculate the derivative of the softmax function

python - Selenium Python : clicking links produced by JSON application