【问题标题】:How to test image upload on Django Rest Framework如何在 Django Rest Framework 上测试图像上传
【发布时间】:2021-05-19 14:54:15
【问题描述】:

我在挣扎。问题在于单元测试(“test.py”),我想出了如何使用 tempfilePIL 上传图像,但这些临时图像永远不会被删除。我考虑创建一个临时目录,然后使用 os.remove 删除该 temp_dir,但图像上传到不同的媒体目录取决于模型,所以我真的不知道如何发布 temp_images然后删除它们。

这是我的 models.py

class Noticia(models.Model):
  ...
  img = models.ImageField(upload_to="noticias", storage=OverwriteStorage(), default="noticias/tanque_arma3.jpg")
  ...

test.py

def temporary_image():
    import tempfile
    from PIL import Image

    image = Image.new('RGB', (100, 100))
    tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg', prefix="test_img_")
    image.save(tmp_file, 'jpeg')
    tmp_file.seek(0)
    return tmp_file

class NoticiaTest(APITestCase):
    def setUp(self):
        ...
        url = reverse('api:noticia-create')
        data = {'usuario': usuario.pk, "titulo":"test", "subtitulo":"test", "descripcion":"test", "img": temporary_image()}
        response = client.post(url, data,format="multipart")

        ...

所以,总而言之,问题是,¿我如何从不同目录中删除临时文件,考虑到这些文件必须严格上传到这些目录上?

【问题讨论】:

标签: python django django-rest-framework temporary-files


【解决方案1】:

您可以使用包dj-inmemorystorage 进行测试,Django 不会保存到磁盘。序列化程序和模型仍将按预期工作,如果需要,您可以将数据读回。

在您的设置中,当您处于测试模式时,覆盖默认文件存储。您还可以在此处放置任何其他“测试模式”设置,只要确保它在您的其他设置之后运行。

if 'test' in sys.argv :
    # store files in memory, no cleanup after tests are finished
    DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage'
    # much faster password hashing, default one is super slow (on purpose)
    PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher']

当您上传文件时,您可以使用SimpleUploadFile,它纯粹是在内存中的。这负责“客户端”端,而 dj-inmemorystorage 包负责 Django 的存储。

def temporary_image():
    bts = BytesIO()
    img = Image.new("RGB", (100, 100))
    img.save(bts, 'jpeg')
    return SimpleUploadedFile("test.jpg", bts.getvalue())

【讨论】:

  • 太棒了!谢谢,但是当我尝试将 'dj-inmemorystorage' 添加到 INSTALLED_APPS 和然后 makemigrations 它说 没有名为 dj-inmemorystorage 的模块。另一个问题是,¿我必须如何导入 SimpleUploadedFile
  • 您从哪里读到应该将其添加到“已安装的应用程序”?它不是一个 django 应用程序,它只是一个你可以使用的库,比如 Pillow。链接到的 github 页面包含所有使用说明。
  • from django.core.files.uploadedfile import SimpleUploadedFile。如果你用谷歌搜索类名,这是第一个结果。 docs.djangoproject.com/en/2.2/_modules/django/core/files/…
  • 没错,昨天我编码了好几个小时,我的大脑被冻结了。如果你让我将 2 加 2 相加,我可能会说 5。它有效。非常感谢@AndrewBacker
  • Andrew 很抱歉问了这么多问题,但是使用 PASSWORD_HASHERS 测试单元的速度要快得多,为什么我不应该使用它作为默认 HASHER?,也许不安全,所以品尝很棒.只是问,我很生气。
猜你喜欢
  • 1970-01-01
  • 2017-03-31
  • 2016-03-23
  • 2014-12-07
  • 2017-10-23
  • 2014-10-16
  • 2018-01-17
  • 2019-03-24
  • 2018-01-15
相关资源
最近更新 更多