小编Mat*_*oco的帖子

如何在 Django Rest Framework 上测试图像上传

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

\n

这是我的models.py

\n
class Noticia(models.Model):\n  ...\n  img = models.ImageField(upload_to="noticias", storage=OverwriteStorage(), default="noticias/tanque_arma3.jpg")\n  ...\n
Run Code Online (Sandbox Code Playgroud)\n

测试.py

\n
def temporary_image():\n    import tempfile\n    from PIL import Image\n\n    image = Image.new(\'RGB\', (100, 100))\n    tmp_file = tempfile.NamedTemporaryFile(suffix=\'.jpg\', prefix="test_img_")\n    image.save(tmp_file, \'jpeg\')\n    tmp_file.seek(0)\n    return tmp_file\n\nclass NoticiaTest(APITestCase):\n    def setUp(self):\n        ...\n        url = reverse(\'api:noticia-create\')\n        data = {\'usuario\': usuario.pk, "titulo":"test", "subtitulo":"test", "descripcion":"test", "img": temporary_image()}\n        response = client.post(url, data,format="multipart")\n\n        ...\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

python django temporary-files django-rest-framework

5
推荐指数
1
解决办法
3063
查看次数